563

Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code

AboutThisE-Book

EPUBisanopenindustry-standardformatfore-booksHoweversupportforEPUBanditsmanyfeaturesvariesacrossreadingdevicesandapplicationsUseyourdeviceorappsettingstocustomizethepresentationtoyourlikingSettingsthatyoucancustomizeoftenincludefontfontsizesingleordoublecolumnlandscapeorportraitmodeandfiguresthatyoucanclickortaptoenlargeForadditionalinformationaboutthesettingsandfeaturesonyourreadingdeviceorappvisitthedevicemanufacturerrsquosWebsiteManytitlesincludeprogrammingcodeorconfigurationexamplesTo

optimizethepresentationoftheseelementsviewthee-bookinsingle-columnlandscapemodeandadjustthefontsizetothesmallestsettingInadditiontopresentingcodeandconfigurationsinthereflowabletextformatwehaveincludedimagesofthecodethatmimicthepresentationfoundintheprintbookthereforewherethereflowableformatmaycompromisethepresentationofthecodelistingyouwillseealdquoClickheretoviewcodeimagerdquolinkClickthelinktoviewtheprint-fidelitycodeimageToreturntothepreviouspageviewedclicktheBackbuttononyourdeviceorapp

LearnPython3TheHardWayAVerySimpleIntroductiontotheTerrifyingly

BeautifulWorldofComputersandCodeZedAShaw

BostonbullColumbusbullIndianapolisbullNewYorkbullSanFranciscobullAmsterdambullCapeTown

DubaibullLondonbullMadridbullMilanbullMunichbullParisbullMontrealbullTorontobullDelhibullMexicoCity

SatildeoPaulobullSydneybullHongKongbullSeoulbullSingaporebullTaipeibullTokyo

ManyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarksWherethosedesignationsappearinthisbookandthepublisherwasawareofatrademarkclaimthedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals

TheauthorandpublisherhavetakencareinthepreparationofthisbookbutmakenoexpressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissionsNoliabilityisassumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseoftheinformationorprogramscontainedherein

Forinformationaboutbuyingthistitleinbulkquantitiesorforspecialsalesopportunities(whichmayincludeelectronicversionscustomcoverdesignsandcontentparticulartoyourbusinesstraininggoalsmarketingfocusorbrandinginterests)pleasecontactourcorporatesalesdepartmentatcorpsalespearsonedcomor(800)382-3419

Forgovernmentsalesinquiriespleasecontactgovernmentsalespearsonedcom

ForquestionsaboutsalesoutsidetheUSpleasecontactintlcspearsoncom

VisitusontheWebinformitcomaw

LibraryofCongressControlNumber2017940290

Copyrightcopy2017ZedAShaw

AllrightsreservedPrintedintheUnitedStatesofAmericaThispublicationisprotectedbycopyrightandpermissionmustbeobtainedfromthepublisherpriortoanyprohibitedreproductionstorageinaretrievalsystemortransmissioninanyformorbyanymeanselectronicmechanicalphotocopyingrecordingorlikewiseForinformationregardingpermissionsrequestformsandtheappropriatecontactswithinthePearsonEducationGlobalRightsampPermissionsDepartmentpleasevisitwwwpearsonedcompermissions

ISBN-13978-0-13-469288-3ISBN-100-13-469288-8

117

Contents

Preface

ImprovementsinthePython3EditionTheHardWayIsEasier

ReadingandWritingAttentiontoDetailSpottingDifferencesAskDonrsquotStareDoNotCopy-PasteUsingtheIncludedVideosANoteonPracticeandPersistence

Acknowledgments

Exercise0TheSetupmacOS

macOSWhatYouShouldSeeWindows

WindowsWhatYouShouldSeeLinux

LinuxWhatYouShouldSeeFindingThingsontheInternetWarningsforBeginnersAlternativeTextEditors

Exercise1AGoodFirstProgramWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise2CommentsandPoundCharactersWhatYouShouldSee

StudyDrillsCommonStudentQuestions

Exercise3NumbersandMathWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise4VariablesandNamesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise5MoreVariablesandPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise6StringsandTextWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise7MorePrintingWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise8PrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise9PrintingPrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise10WhatWasThatWhatYouShouldSeeEscapeSequencesStudyDrillsCommonStudentQuestions

Exercise11AskingQuestionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise12PromptingPeopleWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise13ParametersUnpackingVariablesHoldUpFeaturesHaveAnotherNameWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise14PromptingandPassingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise15ReadingFilesWhatYouShouldSeeStudyDrills

CommonStudentQuestions

Exercise16ReadingandWritingFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise17MoreFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise18NamesVariablesCodeFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise19FunctionsandVariablesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise20FunctionsandFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise21FunctionsCanReturnSomethingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise22WhatDoYouKnowSoFarWhatYouAreLearning

Exercise23StringsBytesandCharacterEncodings

InitialResearchSwitchesConventionsandEncodingsDisectingtheOutputDisectingtheCodeEncodingsDeepDiveBreakingIt

Exercise24MorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise25EvenMorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise26CongratulationsTakeaTestCommonStudentQuestions

Exercise27MemorizingLogicTheTruthTermsTheTruthTablesCommonStudentQuestions

Exercise28BooleanPracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise29WhatIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise30ElseandIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise31MakingDecisionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise32LoopsandListsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise33WhileLoopsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise34AccessingElementsofListsStudyDrills

Exercise35BranchesandFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise36DesigningandDebuggingRulesforif-statementsRulesforLoopsTipsforDebuggingHomework

Exercise37SymbolReview

KeywordsDataTypesStringEscapeSequencesOldStyleStringFormatsOperatorsReadingCodeStudyDrillsCommonStudentQuestions

Exercise38DoingThingstoListsWhatYouShouldSeeWhatListsCanDoWhentoUseListsStudyDrillsCommonStudentQuestions

Exercise39DictionariesOhLovelyDictionariesADictionaryExampleWhatYouShouldSeeWhatDictionariesCanDoStudyDrillsCommonStudentQuestions

Exercise40ModulesClassesandObjectsModulesAreLikeDictionaries

ClassesAreLikeModulesObjectsAreLikeImportGettingThingsfromThingsAFirstClassExample

WhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise41LearningtoSpeakObject-OrientedWordDrillsPhraseDrillsCombinedDrillsAReadingTestPracticeEnglishtoCodeReadingMoreCodeCommonStudentQuestions

Exercise42Is-AHas-AObjectsandClassesHowThisLooksinCodeAboutclassName(object)StudyDrillsCommonStudentQuestions

Exercise43BasicObject-OrientedAnalysisandDesignTheAnalysisofaSimpleGameEngine

WriteorDrawAbouttheProblemExtractKeyConceptsandResearchThemCreateaClassHierarchyandObjectMapfortheConceptsCodetheClassesandaTesttoRunThemRepeatandRefine

TopDownversusBottomUpTheCodeforldquoGothonsfromPlanetPercal25rdquoWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise44InheritanceversusCompositionWhatIsInheritance

ImplicitInheritanceOverrideExplicitlyAlterBeforeorAfter

AllThreeCombinedTheReasonforsuper()

Usingsuper()with__init__CompositionWhentoUseInheritanceorCompositionStudyDrillsCommonStudentQuestions

Exercise45YouMakeaGameEvaluatingYourGameFunctionStyleClassStyleCodeStyleGoodCommentsEvaluateYourGame

Exercise46AProjectSkeletonmacOSLinuxSetupWindows10SetupCreatingtheSkeletonProjectDirectory

FinalDirectoryStructureTestingYourSetupUsingtheSkeletonRequiredQuizCommonStudentQuestions

Exercise47AutomatedTestingWritingaTestCaseTestingGuidelinesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise48AdvancedUserInputOurGameLexicon

BreakingUpaSentenceLexiconTuplesScanningInputExceptionsandNumbers

ATestFirstChallengeWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise49MakingSentencesMatchandPeekTheSentenceGrammarAWordonExceptionsTheParserCodePlayingwiththeParserWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise50YourFirstWebsiteInstallingflaskMakeaSimpleldquoHelloWorldrdquoProjectWhatrsquosGoingOnFixingErrorsCreateBasicTemplatesStudyDrillsCommonStudentQuestions

Exercise51GettingInputfromaBrowserHowtheWebWorksHowFormsWork

CreatingHTMLFormsCreatingaLayoutTemplateWritingAutomatedTestsforFormsStudyDrillsBreakingIt

Exercise52TheStartofYourWebGameRefactoringtheExercise43GameCreatinganEngineYourFinalExamCommonStudentQuestions

NextStepsHowtoLearnAnyProgrammingLanguage

AdvicefromanOldProgrammer

AppendixCommandLineCrashCourseIntroductionShutUpandShell

HowtoUseThisAppendixYouWillBeMemorizingThings

TheSetupDoThisYouLearnedThisDoMore

PathsFoldersDirectories(pwd)DoThisYouLearnedThisDoMore

IfYouGetLostDoThisYouLearnedThis

MakeaDirectory(mkdir)DoThis

YouLearnedThisDoMore

ChangeDirectory(cd)DoThisYouLearnedThisDoMore

ListDirectory(ls)DoThisYouLearnedThisDoMore

RemoveDirectory(rmdir)DoThisYouLearnedThisDoMore

MovingAround(pushdpopd)DoThisYouLearnedThisDoMore

MakingEmptyFiles(touchNew-Item)DoThisYouLearnedThisDoMore

CopyaFile(cp)DoThisYouLearnedThisDoMore

MovingaFile(mv)DoThisYouLearnedThisDoMore

ViewaFile(lessmore)

DoThisYouLearnedThisDoMore

StreamaFile(cat)DoThisYouLearnedThisDoMore

RemovingaFile(rm)DoThisYouLearnedThisDoMore

ExitingYourTerminal(exit)DoThisYouLearnedThisDoMore

CommandLineNextStepsUnixBashReferencesPowerShellReferences

Index

Preface

ThissimplebookismeanttogetyoustartedinprogrammingThetitlesaysitrsquosthehardwaytolearntowritecodebutitrsquosactuallynotItrsquosonlytheldquohardrdquowaybecauseitusesatechniquecalledinstructionInstructioniswhereItellyoutodoasequenceofcontrolledexercisesdesignedtobuildaskillthroughrepetitionThistechniqueworksverywellwithbeginnerswhoknownothingandneedtoacquirebasicskillsbeforetheycanunderstandmorecomplextopicsItrsquosusedineverythingfrommartialartstomusictoevenbasicmathandreadingskillsThisbookinstructsyouinPythonbyslowlybuildingandestablishingskillsthroughtechniquessuchaspracticeandmemorizationthenapplyingthemtoincreasinglydifficultproblemsBytheendofthebookyouwillhavethetoolsneededtobeginlearningmorecomplexprogrammingtopicsIliketotellpeoplethatmybookgivesyouyourldquoprogrammingblackbeltrdquoWhatthismeansisthatyouknowthebasicswellenoughtonowstartlearningprogrammingIfyouworkhardtakeyourtimeandbuildtheseskillsyouwilllearntocode

ImprovementsinthePython3EditionLearnPython3theHardWaynowusesPython36IrsquovestandardizedonthisversionofPythonbecauseithasanewimprovedstringformattingsystemthatiseasiertousethantheprevious4(or3Iforgetthereweremany)versionsThereareafewproblemswithPython36forbeginnersbutIhelpyounavigatetheseissuesinthebookAparticularlyhairyproblemisthatPython36hasverypoorerrormessagesinsomekeyareasthatIhelpyouunderstandIhavealsoimprovedthevideosbasedonmyexperiencesoverthelastfiveyearsteachingpeoplePythonYoucanwatchthesevideosonlineatinformitcomtitle9780134692883InthepastthevideossimplyletyouwatchmedotheexerciseThePython3editionvideosalsoshowyouhowtobreakmdashandthenfixmdasheveryexerciseThisskilliscalledldquodebuggingrdquoItteachesyouhowtofixproblemsyourunintobutalsohowPythonrunstheprogramsyoursquorecreatingThegoalofthisnewmethodologyistobuildamentalmodelofhowPythonrunsyourcodesoyoucanmoreeasilyfigureoutwhyitrsquosbrokenYoursquollalsolearnmanyusefultricksfordebuggingbrokensoftwareLastthePython3editionfullysupportsMicrosoftWindows10frombeginningtoendThepreviouseditionfocusedmostlyontheUnix-stylesystemssuchasmacOSandLinuxwithWindowsbeingmoreofanafterthoughtAtthetimeIstartedwritingthePython3editionMicrosofthadstartedtotakeopensource

startedwritingthePython3editionMicrosofthadstartedtotakeopensourcetoolsanddevelopersseriouslyanditwasdifficulttoignorethemasaseriousPythondevelopmentplatformThevideosfeatureMicrosoftWindowsusingPythoninvariousscenariosandalsoshowmacOSandLinuxforfullcompatibilityItellyouaboutanygotchasoneachplatformcoverinstallationinstructionsandprovideanyothertipsIcangiveyou

TheHardWayIsEasierWiththehelpofthisbookyouwilldotheincrediblysimplethingsthatallprogrammersdotolearnaprogramminglanguage

1Gothrougheachexercise2Typeineachfileexactly3Makeitrun

ThatrsquositThiswillbeverydifficultatfirstbutstickwithitIfyougothroughthisbookanddoeachexerciseforoneortwohoursanightyouwillhaveagoodfoundationformovingontoanotherbookaboutPythontocontinueyourstudiesThisbookwonrsquotturnyouintoaprogrammerovernightbutitwillgetyoustartedonthepathtolearninghowtocodeThisbookrsquosjobistoteachyouthethreemostessentialskillsthatabeginningprogrammerneedstoknowreadingandwritingattentiontodetailandspottingdifferences

ReadingandWritingIfyouhaveaproblemtypingyouwillhaveaproblemlearningtocodeespeciallyifyouhaveaproblemtypingthefairlyoddcharactersinsourcecodeWithoutthissimpleskillyouwillbeunabletolearneventhemostbasicthingsabouthowsoftwareworksTypingthecodesamplesandgettingthemtorunwillhelpyoulearnthenamesofthesymbolsgetfamiliarwithtypingthemandgetyoureadingthelanguage

AttentiontoDetailTheoneskillthatseparatesgoodprogrammersfrombadprogrammersisattentiontodetailInfactitrsquoswhatseparatesthegoodfromthebadinanyprofessionYoumustpayattentiontothetiniestdetailsofyourworkoryouwillmissimportantelementsofwhatyoucreateInprogrammingthisishowyouendupwithbugsanddifficult-to-usesystemsBygoingthroughthisbookandcopyingeachexampleexactlyyouwillbetrainingyourbraintofocusonthedetailsofwhatyouaredoingasyouare

doingit

SpottingDifferencesAveryimportantskill(thatmostprogrammersdevelopovertime)istheabilitytovisuallynoticedifferencesbetweenthingsAnexperiencedprogrammercantaketwopiecesofcodethatareslightlydifferentandimmediatelystartpointingoutthedifferencesProgrammershaveinventedtoolstomakethiseveneasierbutwewonrsquotbeusinganyoftheseYoufirsthavetotrainyourbrainthehardwaythenusethetoolsWhileyoudotheseexercisestypingeachoneinyouwillmakemistakesItrsquosinevitableevenseasonedprogrammerswouldmakeafewYourjobistocomparewhatyouhavewrittentowhatrsquosrequiredandfixallthedifferencesBydoingsoyouwilltrainyourselftonoticemistakesbugsandotherproblems

AskDonrsquotStareIfyouwritecodeyouwillwritebugsAldquobugrdquomeansadefecterrororproblemwiththecodeyoursquovewrittenThelegendssaythatthiscomesfromanactualmoththatflewintooneofthefirstcomputerscausingittomalfunctionFixingitrequiredldquodebuggingrdquothecomputerIntheworldofsoftwaretherearealotofbugsSomanyLikethatfirstmothyourbugswillbehiddensomewhereinthecodeandyouhavetogofindthemYoucanrsquotjustsitatyourcomputerscreenstaringatthewordsyoursquovewrittenhopingthattheanswerjumpsoutatyouThereisnomoreadditionalinformationyoucangetdoingthatandyouneedadditionalinformationYouneedtogetupandgofindthemothTodothatyouhavetointerrogateyourcodeandaskitwhatisgoingonorlookattheproblemfromadifferentviewInthisbookIfrequentlytellyoutoldquostopstaringandaskrdquoIshowyouhowtomakeyourcodetellyoueverythingitcanaboutwhatrsquosgoingonandhowtoturnthisintopossiblesolutionsIalsoshowyouhowtoseeyourcodeindifferentwayssoyoucangetmoreinformationandinsight

DoNotCopy-PasteYoumusttypeeachoftheseexercisesinmanuallyIfyoucopy-pasteyoumightaswellnotevendothemThepointoftheseexercisesistotrainyourhandsyourbrainandyourmindinhowtoreadwriteandseecodeIfyoucopy-pasteyouarecheatingyourselfoutoftheeffectivenessofthelessons

UsingtheIncludedVideos

LearnPython3theHardWayhasanextensivesetofvideosdemonstratinghowthecodeworksandmostimportantlyhowtobreakitThevideosaretheperfectplacetodemonstratemanycommonerrorsbybreakingthePythoncodeonpurposeandshowingyouhowtofixitIalsowalkthroughthecodeusingdebuggingandinterrogationtricksandtechniquesThevideosarewhereIshowyouhowtoldquostopstaringandaskrdquothecodewhatrsquoswrongYoucanwatchthesevideosonlineatinformitcomtitle9780134692883

ANoteonPracticeandPersistenceWhileyouarestudyingprogrammingIrsquomstudyinghowtoplayguitarIpracticeiteverydayforatleasttwohoursadayIplayscaleschordsandarpeggiosforanhourandthenlearnmusictheoryeartrainingsongsandanythingelseIcanSomedaysIstudyguitarandmusicforeighthoursbecauseIfeellikeitanditrsquosfunTomerepetitivepracticeisnaturalandjusthowtolearnsomethingIknowthattogetgoodatanythingIhavetopracticeeverydayevenifIsuckthatday(whichisoften)oritrsquosdifficultKeeptryingandeventuallyitrsquollbeeasierandfunBetweenthetimethatIwroteLearnPythontheHardWayandLearnRubytheHardWayIdiscovereddrawingandpaintingIfellinlovewithmakingvisualartattheageof39andhavebeenspendingeverydaystudyingitinmuchthesamewaythatIstudiedguitarmusicandprogrammingIcollectedbooksofinstructionalmaterialdidwhatthebookssaidpaintedeverydayandfocusedonenjoyingtheprocessoflearningIambynomeansanldquoartistrdquooreventhatgoodbutIcannowsaythatIcandrawandpaintThesamemethodIrsquomteachingyouinthisbookappliedtomyadventuresinartIfyoubreaktheproblemdownintosmallexercisesandlessonsanddothemeverydayyoucanlearntodoalmostanythingIfyoufocusonslowlyimprovingandenjoyingthelearningprocessthenyouwillbenefitnomatterhowgoodyouareatitAsyoustudythisbookandcontinuewithprogrammingrememberthatanythingworthdoingisdifficultatfirstMaybeyouarethekindofpersonwhoisafraidoffailuresoyougiveupatthefirstsignofdifficultyMaybeyouneverlearnedself-disciplinesoyoucanrsquotdoanythingthatrsquosldquoboringrdquoMaybeyouweretoldthatyouareldquogiftedrdquosoyouneverattemptanythingthatmightmakeyouseemstupidornotaprodigyMaybeyouarecompetitiveandunfairlycompareyourselftosomeonelikemewhorsquosbeenprogrammingformorethan20yearsWhateveryourreasonforwantingtoquitkeepatitForceyourselfIfyourunintoaStudyDrillyoucanrsquotdooralessonyoujustdonotunderstandthenskip

itandcomebacktoitlaterJustkeepgoingbecausewithprogrammingtherersquosthisveryoddthingthathappensAtfirstyouwillnotunderstandanythingItrsquollbeweirdjustlikewithlearninganyhumanlanguageYouwillstrugglewithwordsandnotknowwhatsymbolsarewhatanditrsquollallbeveryconfusingThenonedayBANGmdashyourbrainwillsnapandyouwillsuddenlyldquogetitrdquoIfyoukeepdoingtheexercisesandkeeptryingtounderstandthemyouwillgetitYoumightnotbeamastercoderbutyouwillatleastunderstandhowprogrammingworksIfyougiveupyouwonrsquoteverreachthispointYouwillhitthefirstconfusingthing(whichiseverythingatfirst)andthenstopIfyoukeeptryingkeeptypingitinkeeptryingtounderstanditandreadingaboutityouwilleventuallygetitIfyougothroughthiswholebookandyoustilldonotunderstandhowtocodeatleastyougaveitashotYoucansayyoutriedyourbestandalittlemoreanditdidnrsquotworkoutbutatleastyoutriedYoucanbeproudofthat

RegisteryourcopyofLearnPython3theHardWayontheInformITsiteforconvenientaccesstoupdatesandcorrectionsastheybecomeavailableTostarttheregistrationprocessgotoinformitcomregisterandloginorcreateanaccountEntertheproductISBN(9780134692883)andanswerthesimpleproof-of-purchasequestionThenlookontheRegisteredProductstabforanAccessBonusContentlinknexttothisproductandfollowthatlinktoaccessthebonusmaterials

AcknowledgmentsIwouldliketothankAngelaforhelpingmewiththefirsttwoversionsofthisbookWithoutherIprobablywouldnrsquothavebotheredtofinishitatallShedidthecopyeditingofthefirstdraftandsupportedmeimmenselywhileIwroteitIrsquodalsoliketothankGregNewmanfordoingtheoriginalcoverartBrianShumateforearlywebsitedesignsandallofthepeoplewhoreadthisbookandtookthetimetosendmefeedbackandcorrectionsThankyou

Exercise0TheSetup

ThisexercisehasnocodeItissimplytheexerciseyoucompletetogetyourcomputertorunPythonYoushouldfollowtheseinstructionsasexactlyaspossibleIfyouhaveproblemsfollowingthewritteninstructionsthenwatchtheincludedvideosforyourplatform

WarningIfyoudonotknowhowtousePowerShellonWindowsTerminalonmacOSorbashonLinuxthenyouneedtogolearnthatfirstYoushoulddotheexercisesintheappendixfirstbeforecontinuingwiththeseexercises

macOSDothefollowingtaskstocompletethisexercise

1Gotohttpswwwpythonorgdownloadsreleasepython-360anddownloadtheversiontitledldquoMacOSX64-bit32-bitinstallerrdquoInstallitlikeyouwouldanyothersoftware

2GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3PutAtom(yourtexteditor)inyourdocksoyoucanreachiteasily4FindyourTerminalprogramSearchforitYouwillfindit5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthenameandhittingRETURN

8Typequit()Enterandgetoutofpython369YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryintheTerminal11LearnhowtochangeintoadirectoryintheTerminal12UseyoureditortocreateafileinthisdirectoryMakethefileSaveor

SaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindows14BackinTerminallistthedirectorywithlstoseeyournewlycreatedfile

macOSWhatYouShouldSeeHerersquosmedoingthisonmymacOScomputerinTerminalYourcomputermightbedifferentbutshouldbesimilartothisClickheretoviewcodeimage

$python36

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clangndash700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgt

~$mkdirlpthw

~$cdlpthw

lpthw$ls

Useyourtexteditorheretoedittesttxt

lpthw$ls

testtxt

lpthw$

Windows1GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitYoudonotneedtobetheadministratortodothis

2MakesureyoucangettoAtomeasilybyputtingitonyourdesktopandorinQuickLaunchBothoptionsareavailableduringsetupIfyoucannotrunAtombecauseyourcomputerisnotfastenoughthenseetheAlternativeTextEditorssectionattheendofthisexercise

3RunPowerShellfromtheStartmenuSearchforitandjustpressEntertorunit

4MakeashortcuttoitonyourdesktopandorQuickLaunchforyourconvenience

5RunyourPowerShellprogram(whichIwillcallTerminallater)Itwonrsquotlooklikemuch

6DownloadPython36fromhttpswwwpythonorgdownloadsreleasepython-360andinstallitBesuretochecktheboxthatsaystoaddPython36toyourpath

7InyourPowerShell(Terminal)programrunpythonYourunthingsinTerminalbyjusttypingthenameandpressingEnterIfyoutypepythonanditdoesnotrunthenyouhavetoreinstallPythonandmakesureyouchecktheboxforldquoAddpythontothePATHrdquoItrsquosverysmallsolookcarefully

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinthePowerShell(Terminal)11LearnhowtochangeintoadirectoryinthePowerShell(Terminal)12UseyoureditortocreateafileinthisdirectoryMakethefileSaveorSaveAsandpickthisdirectory

13GobacktoPowerShell(Terminal)usingjustthekeyboardtoswitchwindowsLookitupifyoucanrsquotfigureitout

14BackinPowerShell(Terminal)listthedirectorytoseeyournewlycreatedfile

FromnowonwhenIsayldquoTerminalrdquoorldquoshellrdquoImeanPowerShellandthatrsquoswhatyoushoulduseWhenIrunpython36youcanjusttypepython

WindowsWhatYouShouldSeeClickheretoviewcodeimage

gtpython

gtgtgtquit()

gtmkdirlpthw

gtcdlpthw

Hereyouwoulduseyourtexteditortomaketesttxtinlpthw

gt

gtdir

VolumeindriveCis

VolumeSerialNumberis085C-7E02

DirectoryofCDocumentsandSettingsyoulpthw

040520102332ltDIRgt

040520102332ltDIRgt

0405201023326testtxt

1File(s)6bytes

2Dir(s)14804623360bytesfree

gt

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

LinuxLinuxisavariedoperatingsystemwithmanydifferentwaystoinstallsoftwareIrsquomassumingifyouarerunningLinuxthenyouknowhowtoinstallpackagessohereareyourinstructions

1UseyourpackagemanagertoinstallPython36andifyoucanrsquotthendownloadsourcefromhttpswwwpythonorgdownloadsreleasepython-360andbuildfromsource

2UseyourLinuxpackagemanagerandinstalltheAtomtexteditorIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3MakesureyoucangettoAtomeasilybyputtingitinyourwindowmanagerrsquosmenu

4FindyourTerminalprogramItcouldbecalledGNOMETerminalKonsoleorxterm

5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthecommandnameandpressingEnterIfyoucanrsquotrunpython36tryrunningjustpython

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinTerminal11LearnhowtochangeintoadirectoryinTerminal12UseyoureditortocreateafileinthisdirectoryTypicallyyouwillmake

thefileSaveorSaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindowsLookit

upifyoucanrsquotfigureitout14BackinTerminallistthedirectorytoseeyournewlycreatedfile

LinuxWhatYouShouldSee

Clickheretoviewcodeimage

$python

gtgtgtquit()

$mkdirlpthw

$cdlpthw

Useyourtexteditorheretoedittesttxt

$ls

testtxt

$

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

FindingThingsontheInternetAmajorpartofthisbookislearningtoresearchprogrammingtopicsonlineIrsquolltellyoutoldquosearchforthisontheinternetrdquoandyourjobistouseasearchenginetofindtheanswerThereasonIhaveyousearchinsteadofjustgivingyoutheanswerisbecauseIwantyoutobeanindependentlearnerwhodoesnotneedmybookwhenyoursquoredonewithitIfyoucanfindtheanswerstoyourquestionsonlinethenyouareonestepclosertonotneedingmeandthatismygoalThankstosearchenginessuchasGoogleyoucaneasilyfindanythingItellyoutofindIfIsayldquosearchonlineforthepythonlistfunctionsrdquothenyousimplydothis

1Gotohttpgooglecom2Typepython3listfunctions3Readthewebsiteslistedtofindthebestanswer

WarningsforBeginnersYouaredonewiththisexerciseThisexercisemightbehardforyoudependingonyourfamiliaritywithyourcomputerIfitisdifficulttakethetimetoreadandstudyandgetthroughitbecauseuntilyoucandotheseverybasicthingsyouwillfinditdifficulttogetmuchprogrammingdoneIfsomeonetellsyoutostopataspecificexerciseinthisbookortoskipcertainonesyoushouldignorethatpersonAnyonetryingtohideknowledgefromyouorworsemakeyougetitfromtheminsteadofthroughyourowneffortsistryingtomakeyoudependonthemforyourskillsDonrsquotlistentothemanddotheexercisesanywaysothatyoulearnhowtoeducateyourselfAprogrammerwilleventuallytellyoutousemacOSorLinuxIftheprogrammerlikesfontsandtypographytheyrsquolltellyoutogetamacOScomputerIfhelikescontrolandhasahugebeardhewill(orzewillifyou

computerIfhelikescontrolandhasahugebeardhewill(orzewillifyouprefernon-genderedpronounsforhumanswithbeards)tellyoutoinstallLinuxAgainusewhatevercomputeryouhaverightnowthatworksAllyouneedisaneditoraTerminalandPythonFinallythepurposeofthissetuphelpsyoudothreethingsveryreliablywhileyouworkontheexercises

1Writeexercisesusingthetexteditor2Runtheexercisesyouwrote3Fixthemwhentheyarebroken4Repeat

Anythingelsewillonlyconfuseyousosticktotheplan

AlternativeTextEditorsTexteditorsareveryimportanttoaprogrammerbutasabeginneryouonlyneedasimpleprogrammerrsquostexteditorThesearedifferentfromsoftwareforwritingstoriesandbooksbecausetheyworkwiththeuniqueneedsofcomputercodeIrecommendAtominthisbookbecauseitisfreeandworksnearlyeverywhereHoweverAtommaynotrunwellonyourcomputersoherearesomealternativestotry

ThesearerankedinorderofmostlikelytoworkKeepinmindthattheseprojectsmaybeabandoneddeadornotworkanymoreonyourcomputerIfyoutryoneanditdoesnrsquotworktryanotheroneIrsquovealsolistedtheldquoWorksOnrdquoinorderofmostlikelytoworksoifyoursquoreonWindowsthenlookattheeditorswhereWindowsislistedfirstintheldquoWorksOnrdquocolumnIfyoualreadyknowhowtouseVimorEmacsthenfeelfreetousethemIfyouhaveneverusedVimorEmacsthenavoidthemProgrammersmaytrytoconvinceyoutouseVimorEmacsbutthiswillonlyderailyouYourfocusislearningPythonnotlearningVimorEmacsIfyoutrytouseVimanddonrsquotknowhowtoquitthentypeqorZZIfsomeonetoldyoutouseVimand

theydidnrsquoteventellyouthisthennowyouknowwhyyoushouldnrsquotlistentothemDonotuseanIntegratedDevelopmentEnvironment(IDE)whileyougothroughthisbookRelyingonanIDEmeansthatyoucanrsquotworkwithnewprogramminglanguagesuntilsomecompanydecidestosellyouanIDEforthatlanguageThismeansyoucanrsquotusethatnewlanguageuntilthelanguageislargeenoughtojustifyalucrativecustomerbaseIfyouareconfidentyoucanworkwithonlyaprogrammerrsquostexteditor(likeVimEmacsAtometc)thenyoudonrsquothavetowaitforathirdpartyIDEsareniceinsomesituations(suchasworkingwithagiantexistingcodebase)butbeingaddictedtothemwilllimityourfutureYoushouldalsonotuseIDLEIthasseriouslimitationsinhowitworksandisnrsquotaverygoodpieceofsoftwareAllyouneedisasimpletexteditorashellandPython

Exercise1AGoodFirstProgram

WarningIfyouskippedExercise0thenyouarenotdoingthisbookrightAreyoutryingtouseIDLEoranIDEIsaidnottouseoneinExercise0soyoushouldnotuseoneIfyouskippedExercise0pleasegobacktoitandreadit

YoushouldhavespentagoodamountoftimeinExercise0learninghowtoinstallatexteditorrunthetexteditorruntheTerminalandworkwithbothofthemIfyouhavenrsquotdonethatthendonotgoonYouwillnothaveagoodtimeThisistheonlytimeIrsquollstartanexercisewithawarningthatyoushouldnotskiporgetaheadofyourselfTypethefollowingtextintoasinglefilenamedex1pyPythonworksbestwithfilesendinginpyClickheretoviewcodeimage

ex1py

1print(HelloWorld)

2print(HelloAgain)

3print(Iliketypingthis)

4print(Thisisfun)

5print(YayPrinting)

6print(Idmuchratheryounot)

7print(Isaiddonottouchthis)

YourAtomtexteditorshouldlooksomethinglikethisonallplatforms

DonrsquotworryifyoureditordoesnrsquotlookexactlythesameitshouldbeclosethoughYoumayhaveaslightlydifferentwindowheadermaybeslightlydifferentcolorsandtheleftsideofyourAtomwindowwonrsquotsayldquozedshawrdquobutwillinsteadshowthedirectoryyouusedforsavingyourfilesAllofthosedifferencesarefineWhenyoucreatethisfilekeepinmindthesepoints

1IdidnottypethelinenumbersontheleftThoseareprintedinthebooksoIcantalkaboutspecificlinesbysayingldquoSeeline5rdquoYoudonottypelinenumbersintoPythonscripts

2IhavetheprintatthebeginningofthelineanditlooksexactlythesameaswhatIhaveinex1pyExactlymeansexactlynotkindofsortofthesameEverysinglecharacterhastomatchforittoworkColordoesnrsquot

matteronlythecharactersyoutypeInmacOSTerminalor(maybe)Linuxrunthefilebytyping

python36ex1py

OnWindowsrememberyoualwaystypepythoninsteadofpython36likethis

pythonex1py

IfyoudiditrightthenyoushouldseethesameoutputasIintheWhatYouShouldSeesectionofthisexerciseIfnotyouhavedonesomethingwrongNothecomputerisnotwrong

WhatYouShouldSeeOnmacOSintheTerminalyoushouldseethis

OnWindowsinPowerShellyoushouldseethis

Youmayseedifferentnamesbeforethepython36ex1pycommandbuttheimportantpartisthatyoutypethecommandandseetheoutputisthesameasmineIfyouhaveanerroritwilllooklikethisClickheretoviewcodeimage

$python36pythonex1py

Filepythonex1pyline3

print(Iliketypingthis

^

SyntaxErrorEOLwhilescanningstringliteral

ItrsquosimportantthatyoucanreadtheseerrormessagesbecauseyouwillbemakingmanyofthesemistakesEvenImakemanyofthesemistakesLetrsquoslookatthislinebyline

1WeranourcommandintheTerminaltoruntheex1pyscript2Pythontellsusthatthefileex1pyhasanerroronline3ofex1py3Itprintsthislineofcodeforustoseeit4Thenitputsa^(caret)charactertopointatwheretheproblemisNoticethemissing(double-quote)character

5FinallyitprintsoutaldquoSyntaxErrorrdquoandtellsussomethingaboutwhatmightbetheerrorUsuallytheseareverycrypticbutifyoucopythattext

mightbetheerrorUsuallytheseareverycrypticbutifyoucopythattextintoasearchengineyouwillfindsomeoneelsewhorsquoshadthaterrorandyoucanprobablyfigureouthowtofixit

StudyDrillsTheStudyDrillscontainthingsyoushouldtrytodoIfyoucanrsquotskipitandcomebacklaterForthisexercisetrythesethings

1Makeyourscriptprintanotherline2Makeyourscriptprintonlyoneofthelines3Puta(octothorpe)characteratthebeginningofalineWhatdiditdoTrytofindoutwhatthischaracterdoes

FromnowonIwonrsquotexplainhoweachexerciseworksunlessanexerciseisdifferent

WarningAnldquooctothorperdquoisalsocalledaldquopoundrdquoldquohashrdquoldquomeshrdquooranynumberofothernamesPicktheonethatmakesyouchillout

CommonStudentQuestionsTheseareactualquestionsthatrealstudentshaveaskedwhendoingthisexercise

CanIuseIDLENoyoushoulduseTerminalonmacOSandPowerShellonWindowsjustlikeIhavehereIfyoudonrsquotknowhowtousethosethenyoucangoreadtheappendix

HowdoyougetcolorsinyoureditorSaveyourfilefirstasapyfilesuchasex1pyThenyoursquollhavecolorwhenyoutype

IgetSyntaxErrorinvalidsyntaxwhenIrunex1pyYouareprobablytryingtorunPythonthentryingtotypePythonagainCloseyourTerminalstartitagainandrightawaytypeonlypython36ex1py

Igetcantopenfileex1py[Errno2]NosuchfileordirectoryYouneedtobeinthesamedirectoryasthefileyoucreatedMakesureyouusethecdcommandtogotherefirstForexampleifyousavedyourfileinlpthwex1pythenyouwoulddocdlpthwbeforetryingtorunpython36

ex1pyIfyoudonrsquotknowwhatanyofthatmeansthengothroughtheappendix

MyfiledoesnrsquotrunIjustgetthepromptbackwithnooutputYoumostlikelytookthecodeinmyex1pyfileliterallyandthoughtthatprint(HelloWorld)meanttotypeonlyHelloWorldintothefilewithouttheprintYourfilehastobeexactlylikemine

Exercise2CommentsandPoundCharacters

CommentsareveryimportantinyourprogramsTheyareusedtotellyouwhatsomethingdoesinEnglishandtheyareusedtodisablepartsofyourprogramifyouneedtoremovethemtemporarilyHerersquoshowyouusecommentsinPythonClickheretoviewcodeimage

ex2py

1Acommentthisissoyoucanreadyourprogramlater

2Anythingaftertheisignoredbypython

3

4print(Icouldhavecodelikethis)andthecommentafteris

ignored

5

6Youcanalsouseacommenttodisableorcommentoutcode

7print(Thiswontrun)

8

9print(Thiswillrun)

FromnowonIrsquomgoingtowritecodelikethisItisimportantforyoutounderstandthateverythingdoesnothavetobeliteralYourscreenandprogrammayvisuallylookdifferentbutwhatrsquosimportantisthetextyoutypeintothefileyoursquorewritinginyourtexteditorInfactIcouldworkwithanytexteditorandtheresultswouldbethesame

WhatYouShouldSee

Exercise2Session

$python36ex2py

Icouldhavecodelikethis

Thiswillrun

AgainIrsquomnotgoingtoshowyouscreenshotsofalltheTerminalspossibleYoushouldunderstandthattheprecedingisnotaliteraltranslationofwhatyouroutputshouldlooklikevisuallybutthetextbetweenthefirst$python36andlast$lineswillbewhatyoufocuson

StudyDrills

1Findoutifyouwererightaboutwhatthecharacterdoesandmakesureyouknowwhatitrsquoscalled(octothorpeorpoundcharacter)

2Takeyourex2pyfileandrevieweachlinegoingbackwardStartatthelastlineandcheckeachwordinreverseagainstwhatyoushouldhavetyped

3DidyoufindmoremistakesFixthem4ReadwhatyoutypedaboveoutloudincludingsayingeachcharacterbyitsnameDidyoufindmoremistakesFixthem

CommonStudentQuestionsAreyousureiscalledthepoundcharacterIcallittheoctothorpebecausethatistheonlynamethatnoonecountryusesandthatworksineverycountryEverycountrythinksitsnameforthisonecharacterisboththemostimportantwaytodoitandtheonlywayitrsquosdoneTomethisissimplyarroganceandreallyyrsquoallshouldjustchilloutandfocusonmoreimportantthingslikelearningtocode

Whydoestheinprint(Hithere)notgetignoredTheinthatcodeisinsideastringsoitwillbeputintothestringuntiltheendingcharacterishitPoundcharactersinstringsarejustconsideredcharactersnotcomments

HowdoIcommentoutmultiplelinesPutainfrontofeachoneIcanrsquotfigureouthowtotypeacharacteronmycountryrsquoskeyboardHowdoIdothatSomecountriesusetheALTkeyandcombinationsofotherkeystoprintcharactersforeigntotheirlanguageYoursquollhavetolookonlineinasearchenginetoseehowtotypeit

WhydoIhavetoreadcodebackwardItrsquosatricktomakeyourbrainnotattachmeaningtoeachpartofthecodeanddoingthatmakesyouprocesseachpieceexactlyThisisahandyerror-checkingtechnique

Exercise3NumbersandMath

EveryprogramminglanguagehassomekindofwayofdoingnumbersandmathDonotworryprogrammersfrequentlylieaboutbeingmathgeniuseswhentheyreallyarenrsquotIftheyweremathgeniusestheywouldbedoingmathnotwritingbuggywebframeworkssotheycandriveracecarsThisexercisehaslotsofmathsymbolsLetrsquosnamethemrightawaysoyouknowwhattheyarecalledAsyoutypethisoneinsaythenameWhensayingthemfeelsboringyoucanstopsayingthemHerearethenamesbull+plusbull-minusbullslashbullasteriskbullpercentbullltless-thanbullgtgreater-thanbulllt=less-than-equalbullgt=greater-than-equalNoticehowtheoperationsaremissingAfteryoutypeinthecodeforthisexercisegobackandfigureoutwhateachofthesedoesandcompletethetableForexample+doesadditionClickheretoviewcodeimage

ex3py

1print(Iwillnowcountmychickens)

2

3print(Hens25+306)

4print(Roosters100-2534)

5

6print(NowIwillcounttheeggs)

7

8print(3+2+1-5+42-14+6)

9

10print(Isittruethat3+2lt5-7)

11

12print(3+2lt5-7)

13

14print(Whatis3+23+2)

15print(Whatis5-75-7)

16

17print(OhthatswhyitsFalse)

18

19print(Howaboutsomemore)

20

21print(Isitgreater5gt-2)

22print(Isitgreaterorequal5gt=-2)

23print(Isitlessorequal5lt=-2)Makesureyoutypethis

exactlybeforeyourunitCompareeachlineofyourfiletomyfile

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise3Session

$python36ex3py

Iwillnowcountmychickens

Hens300

Roosters97

NowIwillcounttheeggs

675

Isittruethat3+2lt5-7

False

Whatis3+25

Whatis5-7-2

OhthatswhyitsFalse

Howaboutsomemore

IsitgreaterTrue

IsitgreaterorequalTrue

IsitlessorequalFalse

StudyDrills1Aboveeachlineusethetowriteacommenttoyourselfexplainingwhatthelinedoes

2RememberinExercise0whenyoustartedpython36Startpython36thiswayagainandusingthemathoperatorsusePythonasacalculator

3Findsomethingyouneedtocalculateandwriteanewpyfilethatdoesit

4Rewriteex3pytousefloatingpointnumberssoitrsquosmoreaccurate200isfloatingpoint

CommonStudentQuestionsWhyisthecharacteraldquomodulusrdquoandnotaldquopercentrdquoMostlythatrsquosjusthowthedesignerschosetousethatsymbolInnormalwritingyouarecorrecttoreaditasaldquopercentrdquoInprogrammingthiscalculationistypicallydonewithsimpledivisionandtheoperatorThemodulusisadifferentoperationthatjusthappenstousethesymbol

HowdoesworkAnotherwaytosayitisldquoXdividedbyYwithJ

remainingrdquoForexampleldquo100dividedby16with4remainingrdquoTheresultofistheJpartortheremainingpart

WhatistheorderofoperationsIntheUnitedStatesweuseanacronymcalledPEMDASwhichstandsforParenthesesExponentsMultiplicationDivisionAdditionSubtractionThatrsquostheorderPythonfollowsaswellThemistakepeoplemakewithPEMDASistothinkthisisastrictorderasinldquoDoPthenEthenMthenDthenAthenSrdquoTheactualorderisyoudothemultiplicationanddivision(MampD)inonestepfromlefttorightthenyoudotheadditionandsubtractioninonestepfromlefttorightSoyoucouldrewritePEMDASasPE(MampD)(AampS)

Exercise4VariablesandNames

NowyoucanprintthingswithprintandyoucandomathThenextstepistolearnaboutvariablesInprogrammingavariableisnothingmorethananameforsomethingsimilartohowmynameldquoZedrdquoisanameforldquothehumanwhowrotethisbookrdquoProgrammersusethesevariablenamestomaketheircodereadmorelikeEnglishandbecausetheyhavelousymemoriesIftheydidnrsquotusegoodnamesforthingsintheirsoftwaretheyrsquodgetlostwhentheytriedtoreadtheircodeagainIfyougetstuckwiththisexerciserememberthetricksyouhavebeentaughtsofaroffindingdifferencesandfocusingondetails1WriteacommentaboveeachlineexplainingtoyourselfinEnglishwhatitdoes

2Readyourpyfilebackward3Readyourpyfileoutloudsayingeventhecharacters

Clickheretoviewcodeimage

ex4py

1cars=100

2space_in_a_car=40

3drivers=30

4passengers=90

5cars_not_driven=cars-drivers

6cars_driven=drivers

7carpool_capacity=cars_drivenspace_in_a_car

8average_passengers_per_car=passengerscars_driven

9

10

11print(Therearecarscarsavailable)

12print(Thereareonlydriversdriversavailable)

13print(Therewillbecars_not_drivenemptycarstoday)

14print(Wecantransportcarpool_capacitypeopletoday)

15print(Wehavepassengerstocarpooltoday)

16print(Weneedtoputaboutaverage_passengers_per_car

17ineachcar)

WarningThe_inspace_in_a_cariscalledanunderscorecharacterFindouthowtotypeitifyoudonotalreadyknowWeusethischaracteralotto

putanimaginaryspacebetweenwordsinvariablenames

WhatYouShouldSeeClickheretoviewcodeimage

Exercise4Session

$python36ex4py

Thereare100carsavailable

Thereareonly30driversavailable

Therewillbe70emptycarstoday

Wecantransport1200peopletoday

Wehave90tocarpooltoday

Weneedtoputabout30ineachcar

StudyDrillsWhenIwrotethisprogramthefirsttimeIhadamistakeandPythontoldmeaboutitlikethisClickheretoviewcodeimage

Traceback(mostrecentcalllast)

Fileex4pyline8inltmodulegt

average_passengers_per_car=car_pool_capacitypassenger

NameErrornamecar_pool_capacityisnotdefined

ExplainthiserrorinyourownwordsMakesureyouuselinenumbersandexplainwhyHerearemorestudydrills1Iused40forspace_in_a_carbutisthatnecessaryWhathappensifitrsquosjust4

2Rememberthat40isafloatingpointnumberItrsquosjustanumberwithadecimalpointandyouneed40insteadofjust4sothatitisfloatingpoint

3Writecommentsaboveeachofthevariableassignments4Makesureyouknowwhat=iscalled(equals)andthatitspurposeistogivedata(numbersstringsetc)names(cars_drivenpassengers)

5Rememberthat_isanunderscorecharacter6Tryrunningpython36fromtheTerminalasacalculatorlikeyoudidbeforeandusevariablenamestodoyourcalculationsPopularvariablenamesincludeixandj

CommonStudentQuestions

CommonStudentQuestionsWhatisthedifferencebetween=(single-equal)and==(double-equal)The=(single-equal)assignsthevalueontherighttoavariableontheleftThe==(double-equal)testswhethertwothingshavethesamevalueYoursquolllearnaboutthisinExercise27

Canwewritex=100insteadofx=100YoucanbutitrsquosbadformYoushouldaddspacearoundoperatorslikethissothatitrsquoseasiertoread

WhatdoyoumeanbyldquoreadthefilebackwardrdquoVerysimpleImagineyouhaveafilewith16linesofcodeinitStartatline16andcompareittomyfileatline16Thendoitagainfor15andsoonuntilyoursquovereadthewholefilebackward

Whydidyouuse40forspace_in_a_carItismostlysoyoucanthenfindoutwhatafloatingpointnumberisandaskthisquestionSeetheStudyDrills

Exercise5MoreVariablesandPrinting

NowwersquolldoevenmoretypingofvariablesandprintingthemoutThistimewersquollusesomethingcalledaformatstringEverytimeyouput(double-quotes)aroundapieceoftextyouhavebeenmakingastringAstringishowyoumakesomethingthatyourprogrammightgivetoahumanYouprintstringssavestringstofilessendstringstowebserversamongmanyotherthingsStringsarereallyhandysointhisexerciseyouwilllearnhowtomakestringsthathavevariablesembeddedinthemYouembedvariablesinsideastringbyusingaspecialsequenceandthenputthevariableyouwantinsidethecharactersYoualsomuststartthestringwiththeletterfforldquoformatrdquoasinfHellosomevarThislittlefbeforethe(double-quote)andthecharacterstellPython3ldquoHeythisstringneedstobeformattedPutthesevariablesinthererdquoAsusualjusttypethisinevenifyoudonotunderstanditandmakeitexactlythesameClickheretoviewcodeimage

ex5py

1my_name=ZedAShaw

2my_age=35notalie

3my_height=74inches

4my_weight=180lbs

5my_eyes=Blue

6my_teeth=White

7my_hair=Brown

8

9print(fLetstalkaboutmy_name)

10print(fHesmy_heightinchestall)

11print(fHesmy_weightpoundsheavy)

12print(Actuallythatsnottooheavy)

13print(fHesgotmy_eyeseyesandmy_hairhair)

14print(fHisteethareusuallymy_teethdependingonthe

coffee)

15

16thislineistrickytrytogetitexactlyright

17total=my_age+my_height+my_weight

18print(fIfIaddmy_agemy_heightandmy_weightIget

total)

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise5Session

$python36ex5py

LetstalkaboutZedAShaw

Hes74inchestall

Hes180poundsheavy

Actuallythatsnottooheavy

HesgotBlueeyesandBrownhair

HisteethareusuallyWhitedependingonthecoffee

IfIadd3574and180Iget289

StudyDrills1Changeallthevariablessothereisnomy_infrontofeachoneMakesureyouchangethenameeverywherenotjustwhereyouused=tosetthem

2TrytowritesomevariablesthatconverttheinchesandpoundstocentimetersandkilogramsDonotjusttypeinthemeasurementsWorkoutthemathinPython

CommonStudentQuestionsCanImakeavariablelikethis1=ZedShawNo1isnotavalidvariablenameTheyneedtostartwithacharactersoa1wouldworkbut1willnot

HowcanIroundafloatingpointnumberYoucanusetheround()functionlikethisround(17333)

WhydoesthisnotmakesensetomeTrymakingthenumbersinthisscriptyourmeasurementsItrsquosweirdbuttalkingaboutyourselfwillmakeitseemmorerealAlsoyoursquorejuststartingoutsoitwonrsquotmaketoomuchsenseKeepgoingandmoreexerciseswillexplainitmore

Exercise6StringsandText

WhileyouhavebeenwritingstringsyoustilldonotknowwhattheydoInthisexercisewecreateabunchofvariableswithcomplexstringssoyoucanseewhattheyareforFirstanexplanationofstringsAstringisusuallyabitoftextyouwanttodisplaytosomeoneorldquoexportrdquooutoftheprogramyouarewritingPythonknowsyouwantsomethingtobeastringwhenyouputeither(double-quotes)or(single-quotes)aroundthetextYousawthismanytimeswithyouruseofprintwhenyouputthetextyouwanttogoinsidethestringinsideoraftertheprinttoprintthestringStringscancontainanynumberofvariablesthatareinyourPythonscriptRememberthatavariableisanylineofcodewhereyousetaname=(equal)toavalueInthecodeforthisexercisetypes_of_people=10createsavariablenamedtypes_of_peopleandsetsit=(equal)to10Youcanputthatinanystringwithtypes_of_peopleYoualsoseethatIhavetouseaspecialtypeofstringtoldquoformatrdquoitrsquoscalledanldquof-stringrdquoandlookslikethisClickheretoviewcodeimage

fsomestuffhereavariable

fsomeotherstuffanothervar

Pythonalsohasanotherkindofformattingusingtheformat()syntaxwhichyouseeonline17YoursquollseemeusethatsometimeswhenIwanttoapplyaformattoanalready-createdstringsuchasinaloopWersquollcoverthatmorelaterWewillnowtypeinawholebunchofstringsvariablesandformatsandprintthemWewillalsopracticeusingshortabbreviatedvariablenamesProgrammerslovesavingtimeatyourexpensebyusingannoyinglyshortandcrypticvariablenamessoletrsquosgetyoustartedreadingandwritingthemearlyonClickheretoviewcodeimage

ex6py

1types_of_people=10

2x=fTherearetypes_of_peopletypesofpeople

3

4binary=binary

5do_not=dont

6y=fThosewhoknowbinaryandthosewhodo_not

7

8print(x)

9print(y)

10

11print(fIsaidx)

12print(fIalsosaidy)

13

14hilarious=False

15joke_evaluation=Isntthatjokesofunny

16

17print(joke_evaluationformat(hilarious))

18

19w=Thisistheleftsideof

20e=astringwitharightside

21

22print(w+e)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise6Session

$python36ex6py

Thereare10typesofpeople

Thosewhoknowbinaryandthosewhodont

IsaidThereare10typesofpeople

IalsosaidThosewhoknowbinaryandthosewhodont

IsntthatjokesofunnyFalse

Thisistheleftsideofastringwitharightside

StudyDrills1Gothroughthisprogramandwriteacommentaboveeachlineexplainingit

2FindalltheplaceswhereastringisputinsideastringTherearefourplaces

3AreyousurethereareonlyfourplacesHowdoyouknowMaybeIlikelying

4Explainwhyaddingthetwostringswandewith+makesalongerstring

BreakIt

YouarenowatapointwhereyoucantrytobreakyourcodetoseewhathappensThinkofthisasagametodevisethemostcleverwaytobreakthecodeYoucanalsofindthesimplestwaytobreakitOnceyoubreakthecodeyouthenneedtofixitIfyouhaveafriendthenthetwoofyoucantrytobreakeachotherrsquoscodeandfixitGiveyourfriendyourex6pyfilesotheycanbreaksomethingThenyoutrytofindtheirerrorandfixitHavefunwiththisandrememberthatifyouwrotethiscodeonceyoucandoitagainIfyoutakeyourdamagetoofaryoucanalwaystypeitinagainforextrapractice

CommonStudentQuestionsWhydoyouput(single-quotes)aroundsomestringsandnotothersMostlyitrsquosbecauseofstylebutIrsquolluseasingle-quoteinsideastringthathasdouble-quotesLookatlines6and15toseehowIrsquomdoingthat

Ifyouthoughtthejokewasfunnycouldyouwritehilarious=TrueYesandyoursquolllearnmoreaboutthesebooleanvaluesinExercise27

Exercise7MorePrinting

NowwearegoingtodoabunchofexerciseswhereyoujusttypecodeinandmakeitrunIwonrsquotbeexplainingthisexercisebecauseitismoreofthesameThepurposeistobuildupyourchopsSeeyouinafewexercisesanddonotskipDonotpasteClickheretoviewcodeimage

ex7py

1print(Maryhadalittlelamb)

2print(Itsfleecewaswhiteasformat(snow))

3print(AndeverywherethatMarywent)

4print(10)whatdthatdo

5

6end1=C

7end2=h

8end3=e

9end4=e

10end5=s

11end6=e

12end7=B

13end8=u

14end9=r

15end10=g

16end11=e

17end12=r

18

19watchthatcommaattheendtryremovingittoseewhat

happens

20print(end1+end2+end3+end4+end5+end6end=)

21print(end7+end8+end9+end10+end11+end12)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise7Session

$python36ex7py

Maryhadalittlelamb

Itsfleecewaswhiteassnow

AndeverywherethatMarywent

CheeseBurger

StudyDrillsForthesenextfewexercisesyouwillhavetheexactsameStudyDrills

1Gobackthroughandwriteacommentonwhateachlinedoes2Readeachonebackwardoroutloudtofindyourerrors3Fromnowonwhenyoumakemistakeswritedownonapieceofpaperwhatkindofmistakeyoumade

4Whenyougotothenextexerciselookatthemistakesyouhavemadeandtrynottomaketheminthisnewone

5RememberthateveryonemakesmistakesProgrammersarelikemagicianswhofooleveryoneintothinkingtheyareperfectandneverwrongbutitrsquosallanactTheymakemistakesallthetime

BreakItDidyouhavefunbreakingthecodeinExercise6FromnowonyoursquoregoingtobreakallthecodeyouwriteorafriendrsquoscodeIwonrsquothaveaBreakItsectionexplicitlyineveryexercisebutIwilldothisinalmosteveryvideoYourgoalistofindasmanydifferentwaystobreakyourcodeuntilyougettiredorexhaustallpossibilitiesInsomeexercisesImightpointoutaspecificcommonwaypeoplebreakthatexercisersquoscodebutotherwiseconsiderthisastandingordertoalwaysbreakit

CommonStudentQuestionsWhyareyouusingthevariablenamedsnowThatrsquosactuallynotavariableitisjustastringwiththewordsnowinitAvariablewouldnrsquothavethesingle-quotesaroundit

IsitnormaltowriteanEnglishcommentforeverylineofcodelikeyousaytodoinStudyDrill1Noyouwritecommentsonlytoexplaindifficult-to-understandcodeorwhyyoudidsomethingWhyisusuallymuchmoreimportantandthenyoutrytowritethecodesothatitexplainshowsomethingisbeingdoneonitsownHoweversometimesyouhavetowritesuchnastycodetosolveaproblemthatitdoesneedacommentoneverylineInthiscaseitrsquosstrictlyforyoutopracticetranslatingcodetoEnglish

CanIusesingle-quotesordouble-quotestomakeastringordo

theydodifferentthingsInPythoneitherwaytomakeastringisacceptablealthoughtypicallyyoursquollusesingle-quotesforanyshortstringslikeaorsnow

Exercise8PrintingPrinting

WewillnowseehowtodoamorecomplicatedformattingofastringThiscodelookscomplexbutifyoudoyourcommentsaboveeachlineandbreakeachthingdowntoitspartsyoursquollunderstanditClickheretoviewcodeimage

ex8py

1formatter=

2

3print(formatterformat(1234))

4print(formatterformat(onetwothreefour))

5print(formatterformat(TrueFalseFalseTrue))

6print(formatterformat(formatterformatterformatter

formatter))

7print(formatterformat(

8Tryyour

9Owntexthere

10Maybeapoem

11Orasongaboutfear

12))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise8Session

$python36ex8py

1234

onetwothreefour

TrueFalseFalseTrue

TryyourOwntexthereMaybeapoemOrasongaboutfearInthis

exerciseIrsquomusingsomethingcalledafunctiontoturntheformatter

variableintootherstringsWhenyouseemewrite

formatterformat()Irsquomtellingpythontodothefollowing1Take

theformatterstringdefinedonline1

2Callitsformatfunctionwhichissimilartotellingittodoacommandlinecommandnamedformat

3PasstoformatfourargumentswhichmatchupwiththefoursintheformattervariableThisislikepassingargumentstothecommandlinecommandformat

4TheresultofcallingformatonformatterisanewstringthathasthereplacedwiththefourvariablesThisiswhatprintisnowprintingout

ThatrsquosalotfortheeighthexercisesowhatIwantyoutodoisconsiderthisabrainteaserItrsquosalrightifyoudonrsquotreallyunderstandwhatrsquosgoingonbecausetherestofthebookwillslowlymakethisclearAtthispointtrytostudythisandseewhatrsquosgoingonthenmoveontothenextexercise

StudyDrillsDoyourcheckswritedownyourmistakesandtrynottomakethesamemistakesonthenextexerciseInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIhavetoputquotesaroundonebutnotaroundTrueorFalsePythonrecognizesTrueandFalseaskeywordsrepresentingtheconceptoftrueandfalseIfyouputquotesaroundthemthentheyareturnedintostringsandwonrsquotworkYoursquolllearnmoreabouthowtheseworkinExercise27

CanIuseIDLEtorunthisNoyoushouldlearntousethecommandlineItisessentialtolearningprogrammingandisagoodplacetostartifyouwanttolearnaboutprogrammingIDLEwillfailforyouwhenyougetfurtherinthebook

Exercise9PrintingPrintingPrinting

BynowyoushouldrealizethepatternforthisbookistousemorethanoneexercisetoteachyousomethingnewIstartwithcodethatyoumightnotunderstandthenmoreexercisesexplaintheconceptIfyoudonrsquotunderstandsomethingnowyouwilllaterasyoucompletemoreexercisesWritedownwhatyoudonrsquotunderstandandkeepgoingClickheretoviewcodeimage

ex9py

1Heressomenewstrangestuffremembertypeitexactly

2

3days=MonTueWedThuFriSatSun

4months=JannFebnMarnAprnMaynJunnJulnAug

5

6print(Herearethedaysdays)

7print(Herearethemonthsmonths)

8

9print(

10Theressomethinggoingonhere

11Withthethreedouble-quotes

12Wellbeabletotypeasmuchaswelike

13Even4linesifwewantor5or6

14)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise9Session

$python36ex9py

HerearethedaysMonTueWedThuFriSatSun

HerearethemonthsJan

Feb

Mar

Apr

May

Jun

Jul

Aug

Theressomethinggoingonhere

Withthethreedouble-quotes

Wellbeabletotypeasmuchaswelike

Even4linesifwewantor5or6

StudyDrillsCheckyourworkwritedownyourmistakestrynottomakethemonthenextexerciseAreyoubreakingyourcodeandthenfixingitInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIgetanerrorwhenIputspacesbetweenthethreedouble-quotesYouhavetotypethemlikeandnotmeaningwithnospacesbetweeneachone

WhatifIwantedtostartthemonthsonanewlineYousimplystartthestringwithnlikethisClickheretoviewcodeimagenJannFebnMarnAprnMaynJunnJulnAug

IsitbadthatmyerrorsarealwaysspellingmistakesMostprogrammingerrorsinthebeginning(andevenlater)aresimplespellingmistakestyposorgettingsimplethingsoutoforder

Exercise10WhatWasThat

InExercise9IthrewyousomenewstuffjusttokeepyouonyourtoesIshowedyoutwowaystomakeastringthatgoesacrossmultiplelinesInthefirstwayIputthecharactersn(backslashn)betweenthenamesofthemonthsThesetwocharactersputanewlinecharacterintothestringatthatpointThis(backslash)characterencodesdifficult-to-typecharactersintoastringTherearevariousescapesequencesavailablefordifferentcharactersyoumightwanttouseWersquolltryafewofthesesequencessoyoucanseewhatImeanAnimportantescapesequenceistoescapeasingle-quote()ordouble-quote()Imagineyouhaveastringthatusesdouble-quotesandyouwanttoputadouble-quoteinsidethestringIfyouwriteIunderstandjoethenPythonwillgetconfusedbecauseitwillthinkthedouble-quotesaroundunderstandactuallyendsthestringYouneedawaytotellPythonthatthedouble-quoteinsidethestringisnrsquotarealdouble-quoteTosolvethisproblemyouescapedouble-quotesandsingle-quotessoPythonknowstoincludetheminthestringHerersquosanexampleClickheretoviewcodeimage

Iam62tallescapedoublendashquoteinsidestring

Iam62tallescapesinglendashquoteinsidestringThesecond

wayisbyusingtriple-quoteswhichisjustandworkslikea

stringbutyoualsocanputasmanylinesoftextasyouwantuntil

youtypeagainWersquollalsoplaywiththese

Clickheretoviewcodeimage

ex10py

1tabby_cat=tImtabbedin

2persian_cat=Imsplitnonaline

3backslash_cat=Imacat

4

5fat_cat=

6Illdoalist

7tCatfood

8tFishies

9tCatnipntGrass

10

11

12print(tabby_cat)

13print(persian_cat)

14print(backslash_cat)

15print(fat_cat)

WhatYouShouldSeeLookforthetabcharactersthatyoumadeInthisexercisethespacingisimportanttogetright

$pythonex10py

Imtabbedin

Imsplit

onaline

Imacat

Illdoalist

Catfood

Fishies

Catnip

Grass

EscapeSequencesThisisalloftheescapesequencesPythonsupportsYoumaynotusemanyofthesebutmemorizetheirformatandwhattheydoanywayTrythemoutinsomestringstoseeifyoucanmakethemwork

StudyDrills1Memorizealltheescapesequencesbyputtingthemonflashcards2Use(triple-single-quote)insteadCanyouseewhyyoumightusethatinsteadof

3Combineescapesequencesandformatstringstocreateamorecomplexformat

CommonStudentQuestionsIstillhavenrsquotcompletelyfiguredoutthelastexerciseShouldIcontinueYeskeepgoingInsteadofstoppingtakenoteslistingthingsyoudonrsquotunderstandforeachexercisePeriodicallygothroughyournotesandseeifyoucanfigurethesethingsoutafteryoursquovecompletedmoreexercisesSometimesthoughyoumayneedtogobackafewexercisesanddothemagain

WhatmakesspecialcomparedtotheotheronesItrsquossimplythewayyouwouldwriteoutonebackslash()characterThinkaboutwhyyouwouldneedthis

WhenIwriteornitdoesnrsquotworkThatrsquosbecauseyouareusingaforward-slash()andnotabackslash()Theyaredifferentcharactersthatdoverydifferentthings

IdonrsquotgetStudyDrill3WhatdoyoumeanbyldquocombinerdquoescapesequencesandformatsOneconceptIneedyoutounderstandisthateachoftheseexercisescanbecombinedtosolveproblemsTakewhatyouknowaboutformatstringsandwritesomenewcodethatusesformatstringsandtheescapesequencesfromthisexercise

WhatrsquosbetterorItrsquosentirelybasedonstyleGowiththe(triple-single-quote)stylefornowbutbereadytouseeitherdependingonwhatfeelsbestorwhateveryoneelseisdoing

Exercise11AskingQuestions

NowitistimetopickupthepaceYouaredoingalotofprintingtogetyoufamiliarwithtypingsimplethingsbutthosesimplethingsarefairlyboringWhatwewanttodonowisgetdataintoyourprogramsThisisalittletrickybecauseyouhavetolearntodotwothingsthatmaynotmakesenserightawaybuttrustmeanddoitanywayItwillmakesenseinafewexercisesMostofwhatsoftwaredoesisthefollowing1Takessomekindofinputfromaperson

2Changesit3Printsoutsomethingtoshowhowitchanged

SofaryouhavebeenprintingstringsbutyouhavenrsquotbeenabletogetanyinputfromapersonYoumaynotevenknowwhatldquoinputrdquomeansbuttypethiscodeinanywayandmakeitexactlythesameInthenextexercisewersquolldomoretoexplaininputClickheretoviewcodeimage

ex11py

1print(Howoldareyouend=)

2age=input()

3print(Howtallareyouend=)

4height=input()

5print(Howmuchdoyouweighend=)

6weight=input()

7

8print(fSoyoureageoldheighttallandweight

heavy)

WarningWeputanend=attheendofeachprintlineThistellsprinttonotendthelinewithanewlinecharacterandgotothenextline

WhatYouShouldSeeClickheretoviewcodeimage

Exercise11Session

$python36ex11py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1GoonlineandfindoutwhatPythonrsquosinputdoes2CanyoufindotherwaystouseitTrysomeofthesamplesyoufind3Writeanotherldquoformrdquolikethistoasksomeotherquestions

CommonStudentQuestionsHowdoIgetanumberfromsomeonesoIcandomathThatrsquosalittleadvancedbuttryx=int(input())whichgetsthenumberasastringfrominput()thenconvertsittoanintegerusingint()

Iputmyheightintorawinputlikethisinput(62)butitdoesnrsquotworkDonrsquotputyourheightintheretypeitdirectlyintoyourTerminalFirstgobackandmakethecodeexactlylikemineNextrunthescriptandwhenitpausestypeyourheightinatyourkeyboardThatrsquosallthereistoit

Exercise12PromptingPeople

Whenyoutypedinput()youweretypingthe(and)characterswhichareparenthesischaractersThisissimilartowhenyouusedthemtodoaformatwithextravariablesasinfxyForinputyoucanalsoputinaprompttoshowtoapersonsoheknowswhattotypePutastringthatyouwantforthepromptinsidethe()sothatitlookslikethis

y=input(Name)

ThispromptstheuserwithldquoNamerdquoandputstheresultintothevariableyThisishowyouasksomeoneaquestionandgettheanswerThismeanswecancompletelyrewriteourpreviousexerciseusingjustinputtodoallthepromptingClickheretoviewcodeimage

ex12py

1age=input(Howoldareyou)

2height=input(Howtallareyou)

3weight=input(Howmuchdoyouweigh)

4

5print(fSoyoureageoldheighttallandweight

heavy)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise12Session

$python36ex12py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1InTerminalwhereyounormallyrunpython36torunyourscriptstypepydocinputReadwhatitsaysIfyoursquoreonWindowstry

python36-mpydocinputinstead2Getoutofpydocbytypingqtoquit3Lookonlineforwhatthepydoccommanddoes4UsepydoctoalsoreadaboutopenfileosandsysItrsquosalrightifyoudonotunderstandthosejustreadthroughandtakenotesaboutinterestingthings

CommonStudentQuestionsHowcomeIgetSyntaxErrorinvalidsyntaxwheneverIrunpydocYouarenrsquotrunningpydocfromthecommandlineyoursquoreprobablyrunningitfrominsidepython36Exitoutofpython36first

WhydoesmypydocnotpauselikeyoursdoesSometimesifthehelpdocumentisshortenoughtofitononescreenthenpydocwilljustprintit

WhenIrunpydocIgetmoreisnotrecognizedasaninternalSomeversionsofWindowsdonothavethatcommandwhichmeanspydocisbrokenforyouYoucanskipthisStudyDrillandjustsearchonlineforPythondocumentationwhenyouneedit

WhycanrsquotIdoprint(Howoldareyouinput())Youcanbutthentheresultofcallinginput()isneversavedtoavariableanditrsquollworkinastrangewayTrythisandthentrytoprintoutwhatyoutypeSeeifyoucandebugwhythisisnrsquotworking

Exercise13ParametersUnpackingVariables

Inthisexercisewewillcoveronemoreinputmethodyoucanusetopassvariablestoascript(scriptbeinganothernameforyourpyfiles)Youknowhowyoutypepython36ex13pytoruntheex13pyfileWelltheex13pypartofthecommandiscalledanargumentWhatwersquolldonowiswriteascriptthatalsoacceptsargumentsTypethisprogramandIrsquollexplainitindetailClickheretoviewcodeimage

ex13py

1fromsysimportargv

2readtheWYSSsectionforhowtorunthis

3scriptfirstsecondthird=argv

4

5print(Thescriptiscalledscript)

6print(Yourfirstvariableisfirst)

7print(Yoursecondvariableissecond)

8print(Yourthirdvariableisthird)

Online1wehavewhatrsquoscalledanimportThisishowyouaddfeaturestoyourscriptfromthePythonfeaturesetRatherthangiveyouallthefeaturesatoncePythonasksyoutosaywhatyouplantouseThiskeepsyourprogramssmallbutitalsoactsasdocumentationforotherprogrammerswhoreadyourcodelaterTheargvistheargumentvariableaverystandardnameinprogrammingthatyouwillfindusedinmanyotherlanguagesThisvariableholdstheargumentsyoupasstoyourPythonscriptwhenyourunitIntheexercisesyouwillgettoplaywiththismoreandseewhathappensLine3unpacksargvsothatratherthanholdingalltheargumentsitgetsassignedtofourvariablesyoucanworkwithscriptfirstsecondandthirdThismaylookstrangebutldquounpackrdquoisprobablythebestwordtodescribewhatitdoesItjustsaysldquoTakewhateverisinargvunpackitandassignittoallofthesevariablesontheleftinorderrdquoAfterthatwejustprintthemoutlikenormal

HoldUpFeaturesHaveAnotherName

Icallthemldquofeaturesrdquohere(theselittlethingsyouimporttomakeyourPythonprogramdomore)butnobodyelsecallsthemfeaturesIjustusedthatnamebecauseIneededtotrickyouintolearningwhattheyarewithoutjargonBeforeyoucancontinueyouneedtolearntheirrealnamemodulesFromnowonwewillbecallingtheseldquofeaturesrdquothatweimportmodulesIrsquollsaythingslikeldquoYouwanttoimportthesysmodulerdquoTheyarealsocalledldquolibrariesrdquobyotherprogrammersbutletrsquosjuststickwithmodules

WhatYouShouldSee

WarningPayattentionYouhavebeenrunningpythonscriptswithoutcommandlineargumentsIfyoutypeonlypython36ex13pyyouaredoingitwrongPaycloseattentiontohowIrunitThisappliesanytimeyouseeargvbeingused

Runtheprogramlikethis(andyoumustpassthreecommandlinearguments)Clickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd3rd

Thescriptiscalledex13py

Yourfirstvariableisfirst

Yoursecondvariableis2nd

Yourthirdvariableis3rd

ThisiswhatyoushouldseewhenyoudoafewdifferentrunswithdifferentargumentsClickheretoviewcodeimage

Exercise13Session

$python36ex13pystuffthingsthat

Thescriptiscalledex13py

Yourfirstvariableisstuff

Yoursecondvariableisthings

Yourthirdvariableisthat

$

$python36ex13pyappleorangegrapefruit

Thescriptiscalledex13py

Yourfirstvariableisapple

Yoursecondvariableisorange

Yourthirdvariableisgrapefruit

Youcanactuallyreplacefirst2ndand3rdwithanythreethingsyouwantIfyoudonotrunitcorrectlythenyouwillgetanerrorlikethisClickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd

Traceback(mostrecentcalllast)

Fileex13pyline3inltmodulegt

scriptfirstsecondthird=argv

ValueErrornotenoughvaluestounpack(expected4got3)

Thishappenswhenyoudonotputenoughargumentsonthecommandwhenyourunit(inthiscasejustfirst2nd)NoticethatwhenIrunitIgiveitfirst2ndwhichcausedittogiveanerroraboutldquoneedmorethan3valuestounpackrdquotellingyouthatyoudidnrsquotgiveitenoughparameters

StudyDrills1TrygivingfewerthanthreeargumentstoyourscriptSeethaterroryougetSeeifyoucanexplainit

2WriteascriptthathasfewerargumentsandonethathasmoreMakesureyougivetheunpackedvariablesgoodnames

3CombineinputwithargvtomakeascriptthatgetsmoreinputfromauserDonrsquotoverthinkitJustuseargvtogetsomethingandinputtogetsomethingelsefromtheuser

4RememberthatmodulesgiveyoufeaturesModulesModulesRememberthisbecausewersquollneeditlater

CommonStudentQuestionsWhenIrunitIgetValueErrorneedmorethan1valuetounpackRememberthatanimportantskillispayingattentiontodetailsIfyoulookattheWhatYouShouldSeesectionyouseethatIrunthescriptwithparametersonthecommandlineYoushouldreplicatehowIranitexactly

Whatrsquosthedifferencebetweenargvandinput()ThedifferencehastodowithwheretheuserisrequiredtogiveinputIftheygiveyourscriptinputsonthecommandlinethenyouuseargvIfyouwantthemtoinputusingthekeyboardwhilethescriptisrunningthenuseinput()

ArethecommandlineargumentsstringsYestheycomeinasstringsevenifyoutypednumbersonthecommandlineUseint()toconvertthemlikewithint(input())

HowdoyouusethecommandlineYoushouldhavelearnedtouseitveryquicklyandfluentlybynowbutifyouneedtolearnitatthisstagethenreadtheappendix

Icanrsquotcombineargvwithinput()DonrsquotoverthinkitJustslaptwolinesattheendofthisscriptthatuseinput()togetsomethingandthenprintitFromthatstartplayingwithmorewaystousebothinthesamescript

WhycanrsquotIdothisinput()=xBecausethatrsquosbackwardtohowitshouldworkDoitthewayIdoitanditrsquollwork

Exercise14PromptingandPassing

LetrsquosdooneexercisethatusesargvandinputtogethertoasktheusersomethingspecificYouwillneedthisforthenextexercisewhereyoulearntoreadandwritefilesInthisexercisewersquolluseinputslightlydifferentlybyhavingitprintasimplegtpromptThisissimilartogameslikeZorkorAdventureClickheretoviewcodeimage

ex14py

1fromsysimportargv

2

3scriptuser_name=argv

4prompt=gt

5

6print(fHiuser_nameImthescriptscript)

7print(Idliketoaskyouafewquestions)

8print(fDoyoulikemeuser_name)

9likes=input(prompt)

10

11print(fWheredoyouliveuser_name)

12lives=input(prompt)

13

14print(Whatkindofcomputerdoyouhave)

15computer=input(prompt)

16

17print(f

18Alrightsoyousaidlikesaboutlikingme

19YouliveinlivesNotsurewherethatis

20AndyouhaveacomputercomputerNice

21)Wemakeavariablepromptthatissettothepromptwe

wantandwegivethattoinputinsteadoftypingitoverandover

Nowifwewanttomakethepromptsomethingelsewejustchangeit

inthisonespotandrerunthescriptVeryhandy

WhatYouShouldSeeWhenyourunthisrememberthatyouhavetogivethescriptyournamefortheargvargumentsClickheretoviewcodeimage

Exercise14Session

$python36ex14pyzed

HizedImtheex14pyscript

Idliketoaskyouafewquestions

Doyoulikemezed

gtYes

Wheredoyoulivezed

gtSanFrancisco

Whatkindofcomputerdoyouhave

gtTandy1000

AlrightsoyousaidYesaboutlikingme

YouliveinSanFranciscoNotsurewherethatis

AndyouhaveaTandy1000computerNice

StudyDrills1FindoutwhatthegamesZorkandAdventurewereTrytofindcopiesandplaythem

2Changethepromptvariabletosomethingelseentirely3Addanotherargumentanduseitinyourscriptthesamewayyoudidinthepreviousexercisewithfirstsecond=ARGV

4MakesureyouunderstandhowIcombinedastylemultilinestringwiththeformatactivatorasthelastprint

CommonStudentQuestionsIgetSyntaxErrorinvalidsyntaxwhenIrunthisscriptAgainyouhavetorunitrightonthecommandlinenotinsidePythonIfyoutypepython36andthentrytotypepython36ex14pyZeditwillfailbecauseyouarerunningPythoninsidePythonCloseyourwindowandthenjusttypepython36ex14pyZed

IdonrsquotunderstandwhatyoumeanbychangingthepromptSeethevariableprompt=gtChangethattohaveadifferentvalueYouknowthisitrsquosjustastringandyoursquovedone13exercisesmakingthemsotakethetimetofigureitout

IgettheerrorValueErrorneedmorethan1valuetounpackRememberwhenIsaidyouneedtolookattheWhatYouShouldSeesectionandreplicatewhatIdidYouneedtodothesamethinghereandfocusonhowItypethecommandinandwhyIhaveacommandlineargument

HowcanIrunthisfromIDLEDonrsquotuseIDLECanIusedouble-quotesforthepromptvariableYoutotallycanGoaheadandtrythat

YouhaveaTandycomputerIdidwhenIwaslittleIgetNameErrornamepromptisnotdefinedwhenIrunitYoueitherspelledthenameofthepromptvariablewrongorforgotthatlineGobackandcompareeachlineofcodetominestartingatthebottomofthescriptandworkinguptothetopAnytimeyouseethiserroritmeansyouspelledsomethingwrongorforgottocreatethevariable

Exercise15ReadingFiles

YouknowhowtogetinputfromauserwithinputorargvNowyouwilllearnaboutreadingfromafileYoumayhavetoplaywiththisexercisethemosttounderstandwhatrsquosgoingonsodotheexercisecarefullyandrememberyourchecksWorkingwithfilesisaneasywaytoeraseyourworkifyouarenotcarefulThisexerciseinvolveswritingtwofilesOneistheusualex15pyfilethatyouwillrunbuttheotherisnamedex15_sampletxtThissecondfileisnrsquotascriptbutaplaintextfilewersquollbereadinginourscriptHerearethecontentsofthatfileClickheretoviewcodeimage

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

WhatwewanttodoisopenthatfileinourscriptandprintitoutHoweverwedonotwanttojusthardcodethenameex15_sampletxtintoourscriptldquoHardcodingrdquomeansputtingsomebitofinformationthatshouldcomefromtheuserasastringdirectlyinoursourcecodeThatrsquosbadbecausewewantittoloadotherfileslaterThesolutionistouseargvorinputtoasktheuserwhatfiletoopeninsteadofhardcodingthefilersquosnameClickheretoviewcodeimage

ex15py

1fromsysimportargv

2

3scriptfilename=argv

4

5txt=open(filename)

6

7print(fHeresyourfilefilename)

8print(txtread())

9

10print(Typethefilenameagain)

11file_again=input(gt)

12

13txt_again=open(file_again)

14

15print(txt_againread())Afewfancythingsaregoingoninthis

filesoletrsquosbreakitdownrealquicklybullLines1ndash3useargvto

getafilenameNextwehaveline5whereweuseanewcommand

openRightnowrunpydocopenandreadtheinstructionsNotice

howlikeyourownscriptsandinputittakesaparameterand

returnsavalueyoucansettoyourownvariableYoujustopeneda

file

bullLine7printsalittlemessagebutonline8wehavesomethingverynewandexcitingWecallafunctionontxtnamedreadWhatyougetbackfromopenisafileanditalsohascommandsyoucangiveitYougiveafileacommandbyusingthe(dotorperiod)thenameofthecommandandparametersjustlikewithopenandinputThedifferenceisthattxtread()saysldquoHeytxtDoyourreadcommandwithnoparametersrdquo

TheremainderofthefileismoreofthesamebutwersquollleavetheanalysistoyouintheStudyDrills

WhatYouShouldSee

WarningPayattentionIsaidpayattentionYouhavebeenrunningscriptswithjustthenameofthescriptbutnowthatyouareusingargvyouhavetoaddargumentsLookattheveryfirstlineoftheexamplebelowandyouwillseeIdopythonex15pyex15_sampletxttorunitSeetheextraargumentex15_sampletxtaftertheex15pyscriptnameIfyoudonottypethatyouwillgetanerrorsopayattention

Imadeafilecalledex15_sampletxtandranmyscriptClickheretoviewcodeimage

Exercise15Session

$python36ex15pyex15_sampletxt

Heresyourfileex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

Typethefilenameagain

gtex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

StudyDrillsThisisabigjumpsobesureyoudothisStudyDrillasbestyoucanbeforemovingon

1AboveeachlinecommentoutinEnglishwhatthatlinedoes2IfyouarenotsureasksomeoneforhelporsearchonlineManytimessearchingforldquopython36THINGrdquowillfindanswerstowhatthatTHINGdoesinPythonTrysearchingforldquopython36openrdquo

3IusedthewordldquocommandsrdquoherebutcommandsarealsocalledldquofunctionsrdquoandldquomethodsrdquoYouwilllearnaboutfunctionsandmethodslaterinthebook

4Getridoflines10ndash15whereyouuseinputandrunthescriptagain5UseonlyinputandtrythescriptthatwayWhyisonewayofgettingthefilenamebetterthananother

6Startpython36tostartthepython36shellanduseopenfromthepromptjustlikeinthisprogramNoticehowyoucanopenfilesandrunreadonthemfromwithinpython36

7Haveyourscriptalsocallclose()onthetxtandtxt_againvariablesItrsquosimportanttoclosefileswhenyouaredonewiththem

CommonStudentQuestionsDoestxt=open(filename)returnthecontentsofthefileNoitdoesnrsquotItactuallymakessomethingcalledafileobjectYoucanthinkofafilelikeanoldtapedrivethatyousawonmainframecomputersinthe1950sorevenlikeaDVDplayerfromtodayYoucanmovearoundinsidethemandthenldquoreadrdquothembuttheDVDplayerisnottheDVDthesamewaythefileobjectisnotthefilersquoscontents

IcanrsquottypecodeintoTerminalPowerShelllikeyousayinStudyDrill7Firstfromthecommandlinejusttypepython36andpressEnterNowyouareinpython36aswersquovedoneafewothertimesThenyoucantypeincodeandPythonwillrunitinlittlepiecesPlaywiththatTogetoutofittypequit()andhitEnter

WhyistherenoerrorwhenweopenthefiletwicePythonwillnotrestrictyoufromopeningafilemorethanonceandsometimesthisisnecessary

WhatdoesfromsysimportargvmeanFornowjustunderstandthatsysisapackageandthisphrasejustsaystogettheargvfeaturefromthatpackageYoursquolllearnmoreabouttheselater

Iputthenameofthefileinasscriptex15_sampletxt=argvbutitdoesnrsquotworkNothatrsquosnothowyoudoitMakethecodeexactlylikeminethenrunitfromthecommandlinetheexactsamewayIdoYoudonrsquotputthenamesoffilesinyouletPythonputthenamein

Exercise16ReadingandWritingFiles

IfyoudidtheStudyDrillsfromthelastexerciseyoushouldhaveseenallsortsofcommands(methodsfunctions)youcangivetofilesHerersquosthelistofcommandsIwantyoutorememberbullcloseClosesthefileLikeFile-gtSaveinyoureditor

bullreadReadsthecontentsofthefileYoucanassigntheresulttoavariable

bullreadlineReadsjustonelineofatextfilebulltruncateEmptiesthefileWatchoutifyoucareaboutthefilebullwrite(stuff)Writesldquostuffrdquotothefilebullseek(0)Movesthereadwritelocationtothebeginningofthefile

OnewaytorememberwhateachofthesedoesistothinkofavinylrecordcassettetapeVHStapeDVDorCDplayerIntheearlydaysofcomputersdatawasstoredoneachofthesekindsofmediasomanyofthefileoperationsstillresembleastoragesystemthatislinearTapeandDVDdrivesneedtoldquoseekrdquoaspecificspotandthenyoucanreadorwriteatthatspotTodaywehaveoperatingsystemsandstoragemediathatblurthelinesbetweenrandomaccessmemoryanddiskdrivesbutwestillusetheolderideaofalineartapewithareadwriteheadthatmustbemovedFornowthesearetheimportantcommandsyouneedtoknowSomeofthemtakeparametersbutwedonotreallycareaboutthatYouonlyneedtorememberthatwritetakesaparameterofastringyouwanttowritetothefileLetrsquosusesomeofthistomakeasimplelittletexteditorClickheretoviewcodeimage

ex16py

1fromsysimportargv

2

3scriptfilename=argv

4

5print(fWeregoingtoerasefilename)

6print(IfyoudontwantthathitCTRL-C(^C))

7print(IfyoudowantthathitRETURN)

8

9input()

10

11print(Openingthefile)

12target=open(filenamew)

13

14print(TruncatingthefileGoodbye)

15targettruncate()

16

17print(NowImgoingtoaskyouforthreelines)

18

19line1=input(line1)

20line2=input(line2)

21line3=input(line3)

22

23print(Imgoingtowritethesetothefile)

24

25targetwrite(line1)

26targetwrite(n)

27targetwrite(line2)

28targetwrite(n)

29targetwrite(line3)

30targetwrite(n)

31

32print(Andfinallywecloseit)

33targetclose()

ThatrsquosalargefileprobablythelargestyouhavetypedinSogoslowdoyourchecksandmakeitrunOnetrickistogetbitsofitrunningatatimeGetlines1ndash8runningthenfivemorethenafewmoreuntilitrsquosalldoneandrunning

WhatYouShouldSeeThereareactuallytwothingsyouwillseeFirsttheoutputofyournewscriptClickheretoviewcodeimage

Exercise16Session

$python36ex16pytesttxt

Weregoingtoerasetesttxt

IfyoudontwantthathitCTRL-C(^C)

IfyoudowantthathitRETURN

Openingthefile

TruncatingthefileGoodbye

NowImgoingtoaskyouforthreelines

line1Maryhadalittlelamb

line2Itsfleecewaswhiteassnow

line3Itwasalsotasty

Imgoingtowritethesetothefile

Andfinallywecloseit

Nowopenupthefileyoumade(inmycasetesttxt)inyoureditorandcheckitoutNeatright

StudyDrills1IfyoudonotunderstandthisgobackthroughandusethecommenttricktogetitsquaredawayinyourmindOnesimpleEnglishcommentaboveeachlinewillhelpyouunderstandoratleastletyouknowwhatyouneedtoresearchmore

2Writeascriptsimilartothelastexercisethatusesreadandargvtoreadthefileyoujustcreated

3TherersquostoomuchrepetitioninthisfileUsestringsformatsandescapestoprintoutline1line2andline3withjustonetargetwrite()commandinsteadofsix

4FindoutwhywehadtopassawasanextraparametertoopenHintopentriestobesafebymakingyouexplicitlysayyouwanttowriteafile

5Ifyouopenthefilewithwmodethendoyoureallyneedthetargettruncate()ReadthedocumentationforPythonrsquosopenfunctionandseeifthatrsquostrue

CommonStudentQuestionsIsthetruncate()necessarywiththewparameterSeeStudyDrillsnumber5

WhatdoeswmeanItrsquosreallyjustastringwithacharacterinitforthekindofmodeforthefileIfyouusewthenyoursquoresayingldquoopenthisfileinlsquowritersquomoderdquothusthewcharacterTherersquosalsorforldquoreadrdquoaforldquoappendrdquoandmodifiersonthese

WhatmodifierstothefilemodescanIuseThemostimportantonetoknowfornowisthe+modifiersoyoucandow+r+anda+Thiswillopenthefileinbothreadandwritemodeanddependingonthecharacterusepositionthefileindifferentways

Doesjustdoingopen(filename)openitinr(read)modeYesthatrsquosthedefaultfortheopen()function

Exercise17MoreFiles

NowletrsquosdoafewmorethingswithfilesWersquollwriteaPythonscripttocopyonefiletoanotherItrsquollbeveryshortbutwillgiveyouideasaboutotherthingsyoucandowithfilesClickheretoviewcodeimage

ex17py

1fromsysimportargv

2fromospathimportexists

3

4scriptfrom_fileto_file=argv

5

6print(fCopyingfromfrom_filetoto_file)

7

8wecoulddothesetwoononelinehow

9in_file=open(from_file)

10indata=in_fileread()

11

12print(fTheinputfileislen(indata)byteslong)

13

14print(fDoestheoutputfileexistexists(to_file))

15print(ReadyhitRETURNtocontinueCTRL-Ctoabort)

16input()

17

18out_file=open(to_filew)

19out_filewrite(indata)

20

21print(Alrightalldone)

22

23out_fileclose()

24in_fileclose()Youshouldimmediatelynoticethatweimport

anotherhandycommandnamedexistsThisreturnsTrueifafile

existsbasedonitsnameinastringasanargumentItreturns

FalseifnotWersquollbeusingthisfunctioninthesecondhalfofthis

booktodolotsofthingsbutrightnowyoushouldseehowyoucan

importit

Usingimportisawaytogettonsoffreecodeotherbetter(wellusually)programmershavewrittensoyoudonothavetowriteit

WhatYouShouldSee

JustlikeyourotherscriptsrunthisonewithtwoargumentsthefiletocopyfromandthefiletocopyittoIrsquomgoingtouseasimpletestfilenamedtesttxtClickheretoviewcodeimage

Exercise17Session

$firstmakeasamplefile

$echoThisisatestfilegttesttxt

$thenlookatit

$cattesttxt

Thisisatestfile

$nowrunourscriptonit

$python36ex17pytesttxtnew_filetxt

Copyingfromtesttxttonew_filetxt

Theinputfileis21byteslong

DoestheoutputfileexistFalse

ReadyhitRETURNtocontinueCTRL-Ctoabort

Alrightalldone

ItshouldworkwithanyfileTryabunchmoreandseewhathappensJustbecarefulyoudonotblastanimportantfile

WarningDidyouseethetrickIdidwithechotomakeafileandcattoshowthefileYoucanlearnhowtodothatintheAppendixldquoCommandLineCrashCourserdquo

StudyDrills1ThisscriptisreallyannoyingTherersquosnoneedtoaskyoubeforedoingthecopyanditprintstoomuchouttothescreenTrytomakethescriptmorefriendlytousebyremovingfeatures

2SeehowshortyoucanmakethescriptIcouldmakethisonelinelong3NoticeattheendoftheWhatYouShouldSeesectionIusedsomethingcalledcatItrsquosanoldcommandthatconcatenatesfilestogetherbutmostlyitrsquosjustaneasywaytoprintafiletothescreenTypemancattoreadaboutit

4Findoutwhyyouhadtowriteout_fileclose()inthecode

5GoreaduponPythonrsquosimportstatementandstartpython36totryitoutTryimportingsomethingsandseeifyoucangetitrightItrsquosalrightifyoudonot

CommonStudentQuestionsWhyisthewinquotesThatrsquosastringYoursquovebeenusingstringsforawhilenowMakesureyouknowwhatastringis

NowayyoucanmakethisonelineThatdependsonhowyoudefineonelineofcode

IsitnormaltofeellikethisexercisewasreallyhardYesitistotallynormalProgrammingmaynotldquoclickrdquoforyouuntilmaybeevenExercise36oritmightnotuntilyoufinishthebookandthenmakesomethingwithPythonEveryoneisdifferentsojustkeepgoingandkeepreviewingexercisesthatyouhadtroublewithuntilitclicksBepatient

Whatdoesthelen()functiondoItgetsthelengthofthestringthatyoupasstoitthenreturnsthatasanumberPlaywithit

WhenItrytomakethisscriptshorterIgetanerrorwhenIclosethefilesattheendYouprobablydidsomethinglikeindata=open(from_file)read()whichmeansyoudonrsquotneedtothendoin_fileclose()whenyoureachtheendofthescriptItshouldalreadybeclosedbyPythononcethatonelineruns

IgetaSyntaxEOLwhilescanningstringliteralerrorYouforgottoendastringproperlywithaquoteGolookatthatlineagain

Exercise18NamesVariablesCodeFunctions

BigtitlerightIamabouttointroduceyoutothefunctionDumdumdahEveryprogrammerwillgoonandonaboutfunctionsandallthedifferentideasabouthowtheyworkandwhattheydobutIwillgiveyouthesimplestexplanationyoucanuserightnowFunctionsdothreethings1Theynamepiecesofcodethewayvariablesnamestringsandnumbers

2Theytakeargumentsthewayyourscriptstakeargv3Using1and2theyletyoumakeyourownldquomini-scriptsrdquoorldquotinycommandsrdquo

YoucancreateafunctionbyusingtheworddefinPythonIrsquomgoingtohaveyoumakefourdifferentfunctionsthatworklikeyourscriptsandthenIrsquollshowyouhoweachoneisrelatedClickheretoviewcodeimage

ex18py

1thisoneislikeyourscriptswithargv

2defprint_two(args)

3arg1arg2=args

4print(farg1arg1arg2arg2)

5

6okthatargsisactuallypointlesswecanjustdothis

7defprint_two_again(arg1arg2)

8print(farg1arg1arg2arg2)

9

10thisjusttakesoneargument

11defprint_one(arg1)

12print(farg1arg1)

13

14thisonetakesnoarguments

15defprint_none()

16print(Igotnothin)

17

18

19print_two(ZedShaw)

20print_two_again(ZedShaw)

21print_one(First)

22print_none()Letrsquosbreakdownthefirstfunctionprint_two

whichisthemostsimilartowhatyoualreadyknowfrommaking

scripts1WetellPythonwewanttomakeafunctionusingdeffor

ldquodefinerdquo

2OnthesamelineasdefwegivethefunctionanameInthiscasewejustcalleditldquoprint_twordquobutitcouldalsobeldquopeanutsrdquoItdoesnrsquotmatterexceptthatyourfunctionshouldhaveashortnamethatsayswhatitdoes

3Wetellitwewantargs(asteriskargs)whichisalotlikeyourargvparameterbutforfunctionsThishastogoinsideparenthesestowork

4Weendthislinewitha(colon)andstartindenting5Afterthecolonallthelinesthatareindentedfourspaceswillbecomeattachedtoprint_twoOurfirstindentedlineisonethatunpackstheargumentsthesameaswithyourscripts

6Todemonstratehowitworksweprinttheseargumentsoutjustlikewewouldinascript

Theproblemwithprint_twoisthatitrsquosnottheeasiestwaytomakeafunctionInPythonwecanskipthewholeunpackingargumentsandjustusethenameswewantrightinsideparenthesesThatrsquoswhatprint_two_againdoesAfterthatyouhaveanexampleofhowyoumakeafunctionthattakesoneargumentinprint_oneFinallyyouhaveafunctionthathasnoargumentsinprint_none

WarningThisisveryimportantDonotgetdiscouragedrightnowifthisdoesnrsquotquitemakesenseWersquoregoingtodoafewexerciseslinkingfunctionstoyourscriptsandshowyouhowtomakemoreFornowjustkeepthinkingldquomini-scriptrdquowhenIsayldquofunctionrdquoandkeepplayingwiththem

WhatYouShouldSeeIfyourunex18pyyoushouldsee

Exercise18Session

$python36ex18py

arg1Zedarg2Shaw

arg1Zedarg2Shaw

arg1First

Igotnothin

RightawayyoucanseehowafunctionworksNoticethatyouusedyourfunctionsthewayyouusethingslikeexistsopenandothercommandsInfactIrsquovebeentrickingyoubecauseinPythonthosecommandsarejustfunctionsThismeansyoucanmakeyourowncommandsandusetheminyourscriptstoo

StudyDrillsCreateafunctionchecklistforlaterexercisesWritethesechecksonanindexcardandkeepitbyyouwhileyoucompletetherestoftheseexercisesoruntilyoufeelyoudonotneedtheindexcardanymore

1Didyoustartyourfunctiondefinitionwithdef2Doesyourfunctionnamehaveonlycharactersand_(underscore)characters

3Didyouputanopenparenthesisrightafterthefunctionname4Didyouputyourargumentsaftertheparenthesisseparatedbycommas5Didyoumakeeachargumentunique(meaningnoduplicatednames)6Didyouputacloseparenthesisandacolonafterthearguments7DidyouindentalllinesofcodeyouwantinthefunctionfourspacesNomorenoless

8Didyouldquoendrdquoyourfunctionbygoingbacktowritingwithnoindent(dedentingwecallit)

Whenyourun(ldquouserdquoorldquocallrdquo)afunctioncheckthesethings1Didyoucalluserunthisfunctionbytypingitsname

2Didyouputthe(characterafterthenametorunit3Didyouputthevaluesyouwantintotheparenthesesseparatedbycommas

4Didyouendthefunctioncallwitha)characterUsethesetwochecklistsontheremaininglessonsuntilyoudonotneedthemanymoreFinallyrepeatthisafewtimestoyourselfToldquorunrdquoldquocallrdquoorldquouserdquoafunctioneachmeansthesamething

CommonStudentQuestions

CommonStudentQuestionsWhatrsquosallowedforafunctionnameThesameasvariablenamesAnythingthatdoesnrsquotstartwithanumberandislettersnumbersandunderscoreswillwork

WhatdoestheinargsdoThattellsPythontotakealltheargumentstothefunctionandthenputtheminargsasalistItrsquoslikeargvthatyoursquovebeenusingbutforfunctionsItrsquosnotnormallyusedtoooftenunlessspecificallyneeded

ThisfeelsreallyboringandmonotonousThatrsquosgoodItmeansyoursquorestartingtogetbetterattypinginthecodeandunderstandingwhatitdoesTomakeitlessboringtakeeverythingItellyoutotypeinandthenbreakitonpurpose

Exercise19FunctionsandVariables

Functionsmayhavebeenamind-blowingamountofinformationbutdonotworryJustkeepdoingtheseexercisesandgoingthroughyourchecklistfromthelastexerciseandyouwilleventuallygetitThereisonetinypointthatyoumightnothaverealizedwhichwersquollreinforcerightnowThevariablesinyourfunctionarenotconnectedtothevariablesinyourscriptHerersquosanexercisetogetyouthinkingaboutthisClickheretoviewcodeimage

ex19py

1defcheese_and_crackers(cheese_countboxes_of_crackers)

2print(fYouhavecheese_countcheeses)

3print(fYouhaveboxes_of_crackersboxesofcrackers)

4print(Manthatsenoughforaparty)

5print(Getablanketn)

6

7

8print(Wecanjustgivethefunctionnumbersdirectly)

9cheese_and_crackers(2030)

10

11

12print(ORwecanusevariablesfromourscript)

13amount_of_cheese=10

14amount_of_crackers=50

15

16cheese_and_crackers(amount_of_cheeseamount_of_crackers)

17

18

19print(Wecanevendomathinsidetoo)

20cheese_and_crackers(10+205+6)

21

22

23print(Andwecancombinethetwovariablesandmath)

24cheese_and_crackers(amount_of_cheese+100amount_of_crackers

+1000)Thisshowsallthedifferentwayswersquoreabletogiveour

functioncheese_and_crackersthevaluesitneedstoprintthemWe

cangiveitstraightnumbersWecangiveitvariablesWecangive

itmathWecanevencombinemathandvariables

Inawaytheargumentstoafunctionarekindoflikeour=characterwhenwemakeavariableInfactifyoucanuse=tonamesomethingyoucanusually

passittoafunctionasanargument

WhatYouShouldSeeYoushouldstudytheoutputofthisscriptandcompareitwithwhatyouthinkyoushouldgetforeachoftheexamplesinthescriptClickheretoviewcodeimage

Exercise19Session

$python36ex19py

Wecanjustgivethefunctionnumbersdirectly

Youhave20cheeses

Youhave30boxesofcrackers

Manthatsenoughforaparty

Getablanket

ORwecanusevariablesfromourscript

Youhave10cheeses

Youhave50boxesofcrackers

Manthatsenoughforaparty

Getablanket

Wecanevendomathinsidetoo

Youhave30cheeses

Youhave11boxesofcrackers

Manthatsenoughforaparty

Getablanket

Andwecancombinethetwovariablesandmath

Youhave110cheeses

Youhave1050boxesofcrackers

Manthatsenoughforaparty

Getablanket

StudyDrills1GobackthroughthescriptandtypeacommentaboveeachlineexplaininginEnglishwhatitdoes

2Startatthebottomandreadeachlinebackwardsayingalltheimportantcharacters

3Writeatleastonemorefunctionofyourowndesignandrunit10differentways

CommonStudentQuestions

Howcantherepossiblybe10differentwaystorunafunctionBelieveitornottherersquosatheoreticallyinfinitenumberofwaystocallanyfunctionSeehowcreativeyoucangetwithfunctionsvariablesandinputfromauser

IsthereawaytoanalyzewhatthisfunctionisdoingsoIcanunderstanditbetterTherearemanydifferentwaysbuttryputtinganEnglishcommentaboveeachlinedescribingwhatthelinedoesAnothertrickistoreadthecodeoutloudYetanotheristoprintthecodeoutanddrawonthepaperwithpicturesandcommentsshowingwhatrsquosgoingon

WhatifIwanttoasktheuserforthenumbersofcheeseandcrackersYouneedtouseint()toconvertwhatyougetfrominput()

Doesmakingthevariableamount_of_cheesechangethevariablecheese_countinthefunctionNothosevariablesareseparateandliveoutsidethefunctionTheyarethenpassedtothefunctionandtemporaryversionsaremadejustforthefunctionrsquosrunWhenthefunctionexitsthesetemporaryvariablesgoawayandeverythingkeepsworkingKeepgoinginthebookandthisshouldbecomeclearer

Isitbadtohaveglobalvariables(likeamount_of_cheese)withthesamenameasfunctionvariablesYessincethenyoursquorenotquitesurewhichoneyoursquoretalkingaboutButsometimesnecessitymeansyouhavetousethesamenameoryoumightdoitonaccidentJustavoiditwheneveryoucan

IstherealimittothenumberofargumentsafunctioncanhaveItdependsontheversionofPythonandthecomputeryoursquoreonbutitisfairlylargeThepracticallimitthoughisaboutfiveargumentsbeforethefunctionbecomesannoyingtouse

CanyoucallafunctionwithinafunctionYesyoursquollmakeagamethatdoesthislaterinthebook

Exercise20FunctionsandFiles

RememberyourchecklistforfunctionsthendothisexercisepayingcloseattentiontohowfunctionsandfilescanworktogethertomakeusefulstuffClickheretoviewcodeimage

ex20py

1fromsysimportargv

2

3scriptinput_file=argv

4

5defprint_all(f)

6print(fread())

7

8defrewind(f)

9fseek(0)

10

11defprint_a_line(line_countf)

12print(line_countfreadline())

13

14current_file=open(input_file)

15

16print(Firstletsprintthewholefilen)

17

18print_all(current_file)

19

20print(Nowletsrewindkindoflikeatape)

21

22rewind(current_file)

23

24print(Letsprintthreelines)

25

26current_line=1

27print_a_line(current_linecurrent_file)

28

29current_line=current_line+1

30print_a_line(current_linecurrent_file)

31

32current_line=current_line+1

33print_a_line(current_linecurrent_file)Paycloseattentionto

howwepassinthecurrentlinenumbereachtimewerunprint_a_line

WhatYouShouldSee

Clickheretoviewcodeimage

Exercise20Session

$python36ex20pytesttxt

Firstletsprintthewholefile

Thisisline1

Thisisline2

Thisisline3

Nowletsrewindkindoflikeatape

Letsprintthreelines

1Thisisline1

2Thisisline2

3Thisisline3

StudyDrills1WriteanEnglishcommentforeachlinetounderstandwhatthatlinedoes2Eachtimeprint_a_lineisrunyouarepassinginavariablecurrent_lineWriteoutwhatcurrent_lineisequaltooneachfunctioncallandtracehowitbecomesline_countinprint_a_line

3Findeachplaceafunctionisusedandcheckitsdeftomakesurethatyouaregivingittherightarguments

4ResearchonlinewhattheseekfunctionforfiledoesTrypydocfileandseeifyoucanfigureitoutfromthereThentrypydocfileseektoseewhatseekdoes

5Researchtheshorthandnotation+=andrewritethescripttouse+=instead

CommonStudentQuestionsWhatisfintheprint_allandotherfunctionsThefisavariablejustlikeyouhadinotherfunctionsinExercise18exceptthistimeitrsquosafileAfileinPythoniskindoflikeanoldtapedriveonamainframeormaybeaDVDplayerIthasaldquoreadheadrdquoandyoucanldquoseekrdquothisreadheadaroundthefiletopositionsthenworkwithitthereEachtimeyoudofseek(0)yoursquoremovingtothe

startofthefileEachtimeyoudofreadline()yoursquorereadingalinefromthefileandmovingthereadheadtorightafterthenthatendsthatlineThiswillbeexplainedmoreasyougoon

Whydoesseek(0)notsetthecurrent_lineto0Firsttheseek()functionisdealinginbytesnotlinesThecodeseek(0)movesthefiletothe0byte(firstbyte)inthefileSecondcurrent_lineisjustavariableandhasnorealconnectiontothefileatallWearemanuallyincrementingit

Whatis+=YouknowhowinEnglishIcanrewriteldquoitisrdquoasldquoitrsquosrdquoOrIcanrewriteldquoyouarerdquoasldquoyoursquorerdquoInEnglishthisiscalledacontractionandthisiskindoflikeacontractionforthetwooperations=and+Thatmeansx=x+yisthesameasx+=y

Howdoesreadline()knowwhereeachlineisInsidereadline()iscodethatscanseachbyteofthefileuntilitfindsancharacterthenstopsreadingthefiletoreturnwhatitfoundsofarThefilefisresponsibleformaintainingthecurrentpositioninthefileaftereachreadline()callsothatitwillkeepreadingeachline

WhyarethereemptylinesbetweenthelinesinthefileThereadline()functionreturnsthenthatrsquosinthefileattheendofthatlineAddaend=attheendofyourprintfunctioncallstoavoidaddingdoublentoeveryline

Exercise21FunctionsCanReturnSomething

Youhavebeenusingthe=charactertonamevariablesandsetthemtonumbersorstringsWersquorenowgoingtoblowyourmindagainbyshowingyouhowtouse=andanewPythonwordreturntosetvariablestobeavaluefromafunctionTherewillbeonethingtopaycloseattentiontobutfirsttypethisinClickheretoviewcodeimage

ex21py

1defadd(ab)

2print(fADDINGa+b)

3returna+b

4

5defsubtract(ab)

6print(fSUBTRACTINGa-b)

7returna-b

8

9defmultiply(ab)

10print(fMULTIPLYINGab)

11returnab

12

13defdivide(ab)

14print(fDIVIDINGab)

15returnab

16

17

18print(Letsdosomemathwithjustfunctions)

19

20age=add(305)

21height=subtract(784)

22weight=multiply(902)

23iq=divide(1002)

24

25print(fAgeageHeightheightWeightweightIQ

iq)

26

27

28Apuzzlefortheextracredittypeitinanyway

29print(Hereisapuzzle)

30

31what=add(agesubtract(heightmultiply(weightdivide(iq

2))))

32

33print(ThatbecomeswhatCanyoudoitbyhand)Weare

nowdoingourownmathfunctionsforaddsubtractmultiplyand

divideTheimportantthingtonoticeisthelastlinewherewesay

returna+b(inadd)Whatthisdoesisthefollowing1Our

functioniscalledwithtwoargumentsaandb

2WeprintoutwhatourfunctionisdoinginthiscaseldquoADDINGrdquo3WetellPythontodosomethingkindofbackwardwereturntheadditionofa+bYoumightsaythisasldquoIaddaandbthenreturnthemrdquo

4PythonaddsthetwonumbersThenwhenthefunctionendsanylinethatrunsitwillbeabletoassignthisa+bresulttoavariable

AswithmanyotherthingsinthisbookyoushouldtakethisrealslowbreakitdownandtrytotracewhatrsquosgoingonTohelpthereisextracredittosolveapuzzleandlearnsomethingcool

WhatYouShouldSeeClickheretoviewcodeimage

Exercise21Session

$python36ex21py

Letsdosomemathwithjustfunctions

ADDING30+5

SUBTRACTING78-4

MULTIPLYING902

DIVIDING1002

Age35Height74Weight180IQ500

Hereisapuzzle

DIVIDING5002

MULTIPLYING180250

SUBTRACTING74-45000

ADDING35+-44260

Thatbecomes-43910Canyoudoitbyhand

StudyDrills1IfyouarenrsquotreallysurewhatreturndoestrywritingafewofyourownfunctionsandhavethemreturnsomevaluesYoucanreturnanythingthatyoucanputtotherightofan=

2AttheendofthescriptisapuzzleIrsquomtakingthereturnvalueofonefunctionandusingitastheargumentofanotherfunctionIrsquomdoingthisinachainsothatIrsquomkindofcreatingaformulausingthefunctionsItlooks

reallyweirdbutifyourunthescriptyoucanseetheresultsWhatyoushoulddoistrytofigureoutthenormalformulathatwouldrecreatethissamesetofoperations

3OnceyouhavetheformulaworkedoutforthepuzzlegetinthereandseewhathappenswhenyoumodifythepartsofthefunctionsTrytochangeitonpurposetomakeanothervalue

4DotheinverseWriteasimpleformulaandusethefunctionsinthesamewaytocalculateit

ThisexercisemightreallywhackyourbrainoutbuttakeitslowandeasyandtreatitlikealittlegameFiguringoutpuzzleslikethisiswhatmakesprogrammingfunsoIrsquollbegivingyoumorelittleproblemslikethisaswego

CommonStudentQuestionsWhydoesPythonprinttheformulaorthefunctionsldquobackwardrdquoItrsquosnotreallybackwarditrsquosldquoinsideoutrdquoWhenyoustartbreakingdownthefunctionintoseparateformulasandfunctioncallsyoursquollseehowitworksTrytounderstandwhatImeanbyldquoinsideoutrdquoratherthanldquobackwardrdquo

HowcanIuseinput()toentermyownvaluesRememberint(input())Theproblemwiththatisthenyoucanrsquotenterfloatingpointsoalsotryusingfloat(input())instead

WhatdoyoumeanbyldquowriteoutaformulardquoTry24+34100-1023asastartConvertthattousethefunctionsNowcomeupwithyourownsimilarmathequationandusevariablessoitrsquosmorelikeaformula

Exercise22WhatDoYouKnowSoFar

TherewonrsquotbeanycodeinthisexerciseorthenextonesotherersquosnoWhatYouShouldSeeorStudyDrillssectionsInfactthisexerciseislikeonegiantStudyDrillsIrsquomgoingtohaveyoudoareviewofwhatyouhavelearnedsofarFirstgobackthrougheveryexerciseyouhavedonesofarandwritedowneverywordandsymbol(anothernameforldquocharacterrdquo)thatyouhaveusedMakesureyourlistofsymbolsiscompleteNexttoeachwordorsymbolwriteitsnameandwhatitdoesIfyoucanrsquotfindanameforasymbolinthisbookthenlookforitonlineIfyoudonotknowwhatawordorsymboldoesthenreadaboutitagainandtryusingitinsomecodeYoumayrunintoafewthingsyoucanrsquotfindoutorknowsojustkeepthoseonthelistandbereadytolookthemupwhenyoufindthemOnceyouhaveyourlistspendafewdaysrewritingthelistanddouble-checkingthatitrsquoscorrectThismaygetboringbutpushthroughandreallynailitdownOnceyouhavememorizedthelistandwhattheydothenstepitupbywritingouttablesofsymbolstheirnamesandwhattheydofrommemoryIfyouhitsomeyoucanrsquotrecallfrommemorygobackandmemorizethemagain

WarningThemostimportantthingwhendoingthisexerciseisldquoThereisnofailureonlytryingrdquo

WhatYouAreLearningItrsquosimportantwhenyouaredoingaboringmindlessmemorizationexerciselikethistoknowwhyIthelpsyoufocusonagoalandknowthepurposeofallyoureffortsInthisexerciseyouarelearningthenamesofsymbolssothatyoucanreadsourcecodemoreeasilyItrsquossimilartolearningthealphabetandbasicwordsofEnglishexceptthisPythonalphabethasextrasymbolsyoumightnotknowJusttakeitslowanddonothurtyourbrainItrsquosbesttotake15minutesatatimewithyourlistandthentakeabreakGivingyourbrainarestwillhelpyoulearnfasterwithlessfrustration

Exercise23StringsBytesandCharacterEncodings

TodothisexerciseyoursquollneedtodownloadatextfilethatIrsquovewrittennamedlanguagestxt(httpslearnpythonthehardwayorgpython3languagestxt)Thisfilewascreatedwithalistofhumanlanguagestodemonstrateafewinterestingconcepts

1HowmoderncomputersstorehumanlanguagesfordisplayandprocessingandhowPython3callsthisstrings

2HowyoumustldquoencoderdquoandldquodecoderdquoPythonrsquosstringsintoatypecalledbytes

3Howtohandleerrorsinyourstringandbytehandling4Howtoreadcodeandfindoutwhatitmeansevenifyoursquoveneverseenitbefore

InadditiontothatyoursquollalsogetabriefglimpseofthePython3if-statementandlistsforprocessingalistofthingsYoudonrsquothavetomasterthiscodeorunderstandtheseconceptsrightawayYoursquollgetplentyofpracticeinlaterexercisesFornowyourjobistogetatasteofthefutureandlearnthefourtopicsintheprecedinglist

WarningThisexerciseishardTherersquosalotofinformationinitthatyouneedtounderstandanditrsquosinformationthatgoesdeepintocomputersThisexerciseiscomplexbecausePythonrsquosstringsarecomplexanddifficulttouseIrecommendyoutakethisexercisepainfullyslowWritedowneverywordyoudonrsquotunderstandandlookituporresearchitTakeaparagraphatatimeifyoumustYoucancontinuewithotherexerciseswhileyoustudythisonesodonrsquotgetstuckhereJustchipawayatitforaslongasittakes

InitialResearchIrsquomgoingtoteachyouhowtoresearchapieceofcodetoexposeitssecretsYoursquollneedthelanguagestxtfileforthiscodetoworksomakesureyoudownloaditfirstThelanguagestxtfilesimplycontainsalistofhumanlanguagenamesthatareencodedinUTF-8Clickheretoviewcodeimage

ex23py

1importsys

2scriptencodingerror=sysargv

3

4

5defmain(language_fileencodingerrors)

6line=language_filereadline()

7

8ifline

9print_line(lineencodingerrors)

10returnmain(language_fileencodingerrors)

11

12

13defprint_line(lineencodingerrors)

14next_lang=linestrip()

15raw_bytes=next_langencode(encodingerrors=errors)

16cooked_string=raw_bytesdecode(encodingerrors=errors)

17

18print(raw_byteslt===gtcooked_string)

19

20

21languages=open(languagestxtencoding=utf-8)

22

23main(languagesencodingerror)

SimplywritedownalistofeachthingyoursquoveneverseenbeforeTheremaybequiteafewthingsthatarenewsoscanthefileafewtimesOnceyouhavethatyoursquollwanttorunthisPythonscripttoplaywithitHerearesomeexamplecommandsIusedtotestit

WarningYoursquollnoticeIrsquomusingimagesheretoshowyouwhatyoushouldseeAfterextensivetestingitturnsoutthatsomanypeoplehave

seeAfterextensivetestingitturnsoutthatsomanypeoplehavetheircomputersconfiguredtonotdisplayUTF-8thatIhadtouseimagessoyoursquollknowwhattoexpectEvenmyowntypesettingsystem(LaTeX)couldnrsquothandletheseencodingsforcingmetouseimagesinsteadIfyoudonrsquotseethisthenyourTerminalismostlikelynotabletodisplayUTF-8andyoushouldtrytofixthat

Theseexamplesusetheutf-8utf-16andbig5encodingstodemonstratetheconversionandthetypesoferrorsyoucangetEachofthesenamesarecalledaldquocodecrdquoinPython3butyouusetheparameterldquoencodingrdquoAttheendofthisexercisetherersquosalistoftheavailableencodingsifyouwanttotrymoreIrsquollcoverwhatallofthisoutputmeansshortlyYoursquoreonlytryingtogetanideaofhowthisworkssowecantalkaboutitAfteryoursquoverunitafewtimesgothroughyourlistofsymbolsandmakeaguessastowhattheydoWhenyoursquovewrittendownyourguessestrylookingthesymbolsuponlinetoseeifyoucanconfirmyourhypothesesDonrsquotworryifyouhavenoideahowtosearchforthemJustgiveitatry

SwitchesConventionsandEncodingsBeforeIcangetintowhatthiscodemeansyouneedtolearnsomebasicsabouthowdataisstoredinacomputerModerncomputersareincrediblycomplexbutattheircorestheyarelikeahugearrayoflightswitchesComputersuseelectricitytoflipswitchesonoroffTheseswitchescanrepresent1foronor0foroffIntheolddaystherewereallkindsofweirdcomputersthatdidmorethanjust1or0butthesedaysitrsquosjust1sand0sOnerepresentsenergyelectricityonpowersubstanceZerorepresentsoffdonegonepowerdownthelackofenergyWecallthese1sand0sldquobitsrdquoNowacomputerthatonlyletsyouworkwith1and0wouldbebothhorriblyinefficientandincrediblyannoyingComputerstakethese1sand0sandusethemtoencodelargernumbersAtthesmallendacomputerwilluse8ofthese1sand0stoencode256numbers(0-255)WhatdoesldquoencoderdquomeanthoughItrsquosnothingmorethananagreed-uponstandardforhowasequenceofbitsshouldrepresentanumberItrsquosaconventionhumanspickedorstumbledonthatsaysthat00000000wouldbe011111111wouldbe255and00001111wouldbe15TherewereevenhugewarsintheearlyhistoryofcomputersonnothingmorethantheorderofthesebitsbecausetheyweresimplyconventionsweallhadtoagreeonTodaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryone

Todaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryonehadtheirownconventionforabytesoyoursquollstillrunintopeoplewhothinkthatthistermshouldbeflexibleandhandlesequencesof9bits7bitsor6bitsbutnowwejustsayitrsquos8bitsThatrsquosourconventionandthatconventiondefinesourencodingforabyteTherearefutherconventionsforencodinglargenumbersusing163264andevenmorebitsifyougetintoreallybigmathTherersquosentirestandardsgroupswhodonothingbutargueabouttheseconventionsthenimplementthemasencodingsthateventuallyturnswitchesonandoffOnceyouhavebytesyoucanstarttostoreanddisplaytextbydecidingonanotherconventionforhowanumbermapstoaletterIntheearlydaysofcomputingthereweremanyconventionsthatmapped8or7bits(orlessormore)ontolistsofcharacterskeptinsideacomputerThemostpopularconventionendedupbeingAmericanStandardCodeforInformationInterchangeorASCIIThisstandardmapsanumbertoaletterThenumber90isZwhichinbitsis1011010whichgetsmappedtotheASCIItableinsidethecomputerYoucantrythisoutinPythonrightnow

gtgtgt0b1011010

90

gtgtgtord(Z)

90

gtgtgtchr(90)

Z

gtgtgt

FirstIwritethenumber90inbinarythenIgetthenumberbasedontheletterZthenIconvertthenumbertotheletterZDonrsquotworryaboutneedingtorememberthisthoughIthinkIrsquovehadtodoittwicetheentiretimeIrsquoveusedPythonOncewehavetheASCIIconventionforencodingacharacterusing8bits(abyte)wecanthenldquostringrdquothemtogethertomakeawordIfIwanttowritemynameldquoZedAShawrdquoIjustuseasequenceofbytes[90101100326546328310497119]MostoftheearlytextincomputerswasnothingmorethansequencesofbytesstoredinmemorythatacomputerusedtodisplaytexttoapersonAgainthisisjustasequenceofconventionsthatturnedswitchesonandoffTheproblemwithASCIIisthatitonlyencodesEnglishandmaybeafewothersimilarlanguagesRememberthatabytecanhold256numbers(0-255or

00000000-11111111)Turnsouttherersquosalotmorecharactersthan256usedthroughouttheworldrsquoslanguagesDifferentcountriescreatedtheirownencodingconventionsfortheirlanguagesandthatmostlyworkedbutmanyencodingscouldonlyhandleonelanguageThatmeantifyouwanttoputthetitleofanAmericanEnglishbookinthemiddleofaThaisentenceyouwerekindofintroubleYoursquodneedoneencodingforThaiandoneforEnglishTosolvethisproblemagroupofpeoplecreatedUnicodeItsoundslikeldquoencoderdquoanditismeanttobealdquouniversalencodingrdquoofallhumanlanguagesThesolutionUnicodeprovidesisliketheASCIItablebutitrsquoshugebycomparisonYoucanuse32bitstoencodeaUnicodecharacterandthatismorecharactersthanwecouldpossiblyfindA32-bitnumbermeanswecanstore4294967295characters(2^32)whichisenoughspaceforeverypossiblehumanlanguageandprobablyalotofalienonestooRightnowweusetheextraspaceforimportantthingslikepoopandsmileemojisWenowhaveaconventionforencodinganycharacterswewantbut32bitsis4bytes(328==4)whichmeansthereissomuchwastedspaceinmosttextwewanttoencodeWecanalsouse16bits(2bytes)butstilltherersquosgoingtobewastedspaceinmosttextThesolutionistouseacleverconventiontoencodemostcommoncharactersusing8bitsandthenldquoescaperdquointolargernumberswhenweneedtoencodemorecharactersThatmeanswehaveonemoreconventionthatisnothingmorethanacompressionencodingmakingitpossibleformostcommoncharacterstouse8bitsandthenescapeoutinto16or32bitsasneededTheconventionforencodingtextinPythoniscalledldquoUTF-8rdquowhichmeansldquoUnicodeTransformationFormat8BitsrdquoItisaconventionforencodingUnicodecharactersintosequencesofbyteswhicharesequencesofbitswhichturnsequencesofswitchesonandoffYoucanalsouseotherconventions(encodings)butUTF-8isthecurrentstandard

DisectingtheOutputWecannowlookattheoutputofthecommandsshownpreviouslyLetrsquostakejustthatfirstcommandandthefirstfewlinesofoutput

Theex23pyscriptistakingbyteswritteninsidetheb(bytestring)andconvertingthemtotheUTF-8(orother)encodingyouspecifiedOntheleftisthenumbersforeachbyteoftheUTF-8(showninhexadecimal)andtherighthasthecharacteroutputasactualUTF-8Thewaytothinkofthisistheleftsideoflt===gtisthePythonnumericalbytesortheldquorawrdquobytesPythonusestostorethestringYouspecifythiswithbtotellPythonthisisbytesTheserawbytesarethendisplayedldquocookedrdquoontherightsoyoucanseetherealcharactersinyourTerminal

DisectingtheCodeWehaveanunderstandingofstringsandbytesequencesInPythonastringisaUTF-8encodedsequenceofcharactersfordisplayingorworkingwithtextThebytesarethentheldquorawrdquosequenceofbytesthatPythonusestostorethisUTF-8stringandstartwithabtotellPythonyouareworkingwithrawbytesThisisallbasedonconventionsforhowPythonwantstoworkwithtextHerersquosaPythonsessionshowingmeencodingstringsanddecodingbytes

Allyouneedtorememberisifyouhaverawbytesthenyoumustusedecode()togetthestringRawbyteshavenoconventiontothemTheyarejustsequencesofbyteswithnomeaningotherthannumberssoyoumusttellPythontoldquodecodethisintoaUTFstringrdquoIfyouhaveastringandwanttosenditstoreitshareitordosomeotheroperationthenusuallyitrsquollworkbutsometimesPythonwillthrowupanerrorsayingitdoesnrsquotknowhowtoldquoencoderdquoitAgainPythonknowsitsinternalconventionbutithasnoideawhatconventionyouneedInthatcaseyoumustuseencode()togetthebytesyouneedThewaytorememberthis(eventhoughIlookitupalmosteverytime)istorememberthemnemonicDBESwhichstandsforDecodeBytesEncodeStringsIsayldquodeebessrdquoinmyheadwhenIhavetoconvertbytesandstringsWhenyouhavebytesandneedastringdecodebytesWhenyouhaveastringandneedbytesencodestringsWiththatinmindletrsquosbreakdownthecodeinex23pyline-by-line1ndash2Istartwiththeusualcommandlineargumenthandlingthatyoualready

know5IstartthemainmeatofthiscodeinafunctionconvenientlycalledmainThiswillbecalledattheendofthisscripttogetthingsgoing

6ThefirstthingthisfunctiondoesisreadonelinefromthelanguagesfileitisgivenYouhavedonethisbeforesonothingnewhereJustreadlineasbeforewhendealingwithtextfiles

8IusesomethingnewYouwilllearnaboutthisinthesecondhalfofthebooksoconsiderthisateaserofinterestingthingstocomeThisisanif-statementanditletsyoumakedecisionsinyourPythoncodeYoucantestthetruthofavariableandbasedonthattruthrunapieceofcodeornotrunitInthiscaseIrsquomtestingwhetherlinehassomethinginitThereadlinefunctionwillreturnanemptystringwhenitreachestheendofthefileandiflinesimplytestsforthisemptystringAslongasreadlinegivesussomethingthiswillbetrueandthecodeunder(indentedinlines9ndash10)willrunWhenthisisfalsePythonwillskiplines9ndash10

9IcallaseparatefunctiontodotheactualprintingofthislineThissimplifiesmycodeandmakesiteasierformetounderstanditIfIwanttolearnwhatthisfunctiondoesIcanjumptoitandstudyOnceIknowwhatprint_linedoesIcanattachmymemorytothenameprint_line

andforgetaboutthedetails10IhavewrittenatinyyetpowerfulpieceofmagichereIamcallingmainagaininsidemainActuallyitrsquosnotmagicsincenothingreallyismagicalinprogrammingAlltheinformationyouneedisthereThislookslikeIamcallingthefunctioninsideitselfwhichseemslikeitshouldbeillegaltodoAskyourselfwhyshouldthatbeillegalTherersquosnotechnicalreasonwhyIcanrsquotcallanyfunctionIwantrightthereeventhismainfunctionIfafunctionissimplyajumptothetopwhereIrsquovenameditmainthencallingthisfunctionattheendofitselfwouldjumpbacktothetopandrunitagainThatwouldmakeitloopNowlookbackatline8andyoursquollseetheif-statementkeepsthisfunctionfromloopingforeverCarefullystudythisbecauseitisasignificantconceptbutdonrsquotworryifyoucanrsquotgraspitrightaway

13Istartthedefinitionfortheprint_linefunctionwhichdoestheactualencodingofeachlinefromthelanguagestxtfile

14Thisisasimplestrippingofthetrailingnonthelinestring15IfinallytakethelanguageIrsquovereceivedfromthelanguagestxtfileandencodeitintotherawbytesRemembertheDBESmnemonicDecodebytesencodestringsThenext_langvariableisastringsotogettherawbytesImustcallencode()onittoencodestringsIpasstoencode()theencodingIwantandhowtohandleerrors

16Idotheextrastepofshowingtheinverseofline15bycreatingacooked_stringvariablefromtheraw_bytesRememberDBESsaysIdecodebytesandraw_bytesisbytessoIcalldecode()onittogetaPythonstringThisstringshouldbethesameasthenext_langvariable

18Isimplyprintthembothouttoshowyouwhattheylooklike21IrsquomdonedefiningfunctionssonowIwanttoopenthelanguagestxtfile

23Theendofthescriptsimplyrunsthemainfunctionwithallthecorrectparameterstogeteverythinggoingandkick-starttheloopRememberthatthisthenjumpstowherethemainfunctionisdefinedonline5andonline10mainiscalledagaincausingthistokeeploopingTheiflineonline8willpreventourloopfromgoingforever

EncodingsDeepDive

WecannowuseourlittlescripttoexploreotherencodingsThefollowingshowsmeplayingwithdifferentencodingsandseeinghowtobreakthemFirstIrsquomdoingasimpleUTF-16encodingsoyoucanseehowitchangescomparedtoUTF-8YoucanalsouseUTF-32toseehowthatrsquosevenbiggerandgetanideaofthespacesavedwithUTF-8AfterthatItryBig5andyoursquollseethatPythondoesnotlikethatatallItthrowsupanerrorthatBig5canrsquotencodesomeofthecharactersatposition0(whichissuperhelpful)OnesolutionistotellPythontoldquoreplacerdquoanybadcharactersfortheBig5encodingThatrsquosthenextexampleandyoursquollseeitputsacharacterwhereveritfindsacharacterthatdoesnrsquotmatchtheBig5encodingsystem

BreakingItRoughideasincludethefollowing

1Findstringsoftextencodedinotherencodingsandplacethemintheex23pyfiletoseehowitbreaks

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist3ExtrachallengingRewritethisusingthebbytesinsteadoftheUTF-8stringseffectivelyreversingthescript

4IfyoucandothatthenyoucanalsobreakthesebytesbyremovingsometoseewhathappensHowmuchdoyouneedtoremovetocausePythontobreakHowmuchcanyouremovetodamagethestringoutputbutpassPythonrsquosdecodingsystem

5Usewhatyoulearnedfromitem4toseeifyoucanmanglethefilesWhaterrorsdoyougetHowmuchdamagecanyoucauseandgetthefilepastPythonrsquosdecodingsystem

Exercise24MorePractice

YouaregettingtotheendofthissectionYoushouldhaveenoughPythonldquounderyourfingersrdquotomoveontolearningabouthowprogrammingreallyworksbutyoushoulddosomemorepracticeThisexerciseislongerandallaboutbuildingupstaminaThenextexercisewillbesimilarDothemgetthemexactlyrightanddoyourchecksClickheretoviewcodeimage

ex24py

1print(Letspracticeeverything)

2print(Youdneedtoknowboutescapeswiththatdo)

3print(nnewlinesandttabs)

4

5poem=

6tThelovelyworld

7withlogicsofirmlyplanted

8cannotdiscernntheneedsoflove

9norcomprehendpassionfromintuition

10andrequiresanexplanation

11nttwherethereisnone

12

13

14print(--------------)

15print(poem)

16print(--------------)

17

18

19five=10-2+3-6

20print(fThisshouldbefivefive)

21

22defsecret_formula(started)

23jelly_beans=started500

24jars=jelly_beans1000

25crates=jars100

26returnjelly_beansjarscrates

27

28

29start_point=10000

30beansjarscrates=secret_formula(start_point)

31

32rememberthatthisisanotherwaytoformatastring

33print(Withastartingpointofformat(start_point))

34itsjustlikewithanfstring

35print(fWedhavebeansbeansjarsjarsandcrates

crates)

36

37start_point=start_point10

38

39print(Wecanalsodothatthisway)

40formula=secret_formula(start_point)

41thisisaneasywaytoapplyalisttoaformatstring

42print(Wedhavebeansjarsand

cratesformat(formula))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise24Session

$python36ex24py

Letspracticeeverything

Youdneedtoknowboutescapeswiththatdo

newlinesandtabs

--------------

Thelovelyworld

withlogicsofirmlyplanted

cannotdiscern

theneedsoflove

norcomprehendpassionfromintuition

andrequiresanexplanation

wherethereisnone

--------------

Thisshouldbefive5

Withastartingpointof10000

Wedhave5000000beans50000jarsand500crates

Wecanalsodothatthisway

Wedhave5000000beans5000jarsand50crates

StudyDrills1Makesuretodoyourchecksreaditbackwardreaditoutloudandputcommentsaboveconfusingparts

2BreakthefileonpurposethenrunittoseewhatkindsoferrorsyougetMakesureyoucanfixit

CommonStudentQuestionsWhydoyoucallthevariablejelly_beansbutthenamebeanslaterThatrsquospartofhowafunctionworksRememberthatinsidethefunctionthevariableistemporaryWhenyoureturnitthenitcanbeassignedtoavariableforlaterIrsquomjustmakinganewvariablenamedbeanstoholdthereturnvalue

WhatdoyoumeanbyreadingthecodebackwardStartatthelastlineComparethatlineinyourfiletothesamelineinmineOnceitrsquosexactlythesamemoveuptothenextlineDothisuntilyougettothefirstlineofthefile

WhowrotethatpoemIdidNotallofmypoemssuck

Exercise25EvenMorePractice

WersquoregoingtodosomemorepracticeinvolvingfunctionsandvariablestomakesureyouknowthemwellThisexerciseshouldbestraightforwardforyoutotypeinbreakdownandunderstandHoweverthisexerciseisalittledifferentYouwonrsquotberunningitInsteadyouwillimportitintoPythonandrunthefunctionsyourselfClickheretoviewcodeimage

ex25py

1defbreak_words(stuff)

2Thisfunctionwillbreakupwordsforus

3words=stuffsplit()

4returnwords

5

6defsort_words(words)

7Sortsthewords

8returnsorted(words)

9

10defprint_first_word(words)

11Printsthefirstwordafterpoppingitoff

12word=wordspop(0)

13print(word)

14

15defprint_last_word(words)

16Printsthelastwordafterpoppingitoff

17word=wordspop(-1)

18print(word)

19

20defsort_sentence(sentence)

21Takesinafullsentenceandreturnsthesorted

words

22words=break_words(sentence)

23returnsort_words(words)

24

25defprint_first_and_last(sentence)

26Printsthefirstandlastwordsofthesentence

27words=break_words(sentence)

28print_first_word(words)

29print_last_word(words)

30

31defprint_first_and_last_sorted(sentence)

32Sortsthewordsthenprintsthefirstandlastone

33words=sort_sentence(sentence)

34print_first_word(words)

35print_last_word(words)Firstrunthiswithpython36

ex25pytofindanyerrorsyouhavemadeOnceyouhavefoundallof

theerrorsyoucanandfixedthemyouwillthenwanttofollowthe

WhatYouShouldSeesectiontocompletetheexercise

WhatYouShouldSeeInthisexercisewersquoregoingtointeractwithyourex25pyfileinsidethepython36interpreteryouusedperiodicallytodocalculationsYourunpython36fromtheTerminallikethisClickheretoviewcodeimage

$python36

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtYouroutputshouldlooklikemineandafterthegtcharacter

(calledtheprompt)youcantypePythoncodeinanditwillrun

immediatelyUsingthisIwantyoutotypeeachoftheselinesof

Pythoncodeintopython36andseewhatitdoesClickheretoview

codeimage

Exercise25PythonSession

1importex25

2sentence=Allgoodthingscometothosewhowait

3words=ex25break_words(sentence)

4words

5sorted_words=ex25sort_words(words)

6sorted_words

7ex25print_first_word(words)

8ex25print_last_word(words)

9words

10ex25print_first_word(sorted_words)

11ex25print_last_word(sorted_words)

12sorted_words

13sorted_words=ex25sort_sentence(sentence)

14sorted_words

15ex25print_first_and_last(sentence)

16ex25print_first_and_last_sorted(sentence)Herersquoswhatitlooks

likewhenIworkwiththeex25pymoduleinpython36Clickhereto

viewcodeimage

Exercise25PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtimportex25

gtgtgtsentence=Allgoodthingscometothosewhowait

gtgtgtwords=ex25break_words(sentence)

gtgtgtwords

[Allgoodthingscometothosewhowait]

gtgtgtsorted_words=ex25sort_words(words)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_word(words)

All

gtgtgtex25print_last_word(words)

wait

gtgtgtwords

[goodthingscometothosewho]

gtgtgtex25print_first_word(sorted_words)

All

gtgtgtex25print_last_word(sorted_words)

who

gtgtgtsorted_words

[comegoodthingsthosetowait]

gtgtgtsorted_words=ex25sort_sentence(sentence)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_and_last(sentence)

All

wait

gtgtgtex25print_first_and_last_sorted(sentence)

All

whoAsyougothrougheachoftheselinesmakesureyoucanfindthe

functionthatrsquosbeingruninex25pyandunderstandhoweachone

worksIfyougetdifferentresultsorerroryoursquollhavetogofix

yourcodeexitpython36andstartover

StudyDrills1TaketheremaininglinesoftheWhatYouShouldSeeoutputandfigureoutwhattheyaredoingMakesureyouunderstandhowyouarerunningyourfunctionsintheex25module

2Trydoingthishelp(ex25)andalsohelp(ex25break_words)Noticehowyougethelpforyourmoduleandhowthehelpisthoseoddstringsyouputaftereachfunctioninex25Thosespecialstringsarecalleddocumentationcommentsandwersquollbeseeingmoreofthem

3Typingex25isannoyingAshortcutistodoyourimportlikethisfromex25importThisislikesayingldquoImporteverythingfromex25rdquoProgrammerslikesayingthingsbackwardStartanewsessionandseehowallyourfunctionsarerightthere

4TrybreakingyourfileandseewhatitlookslikeinpythonwhenyouuseitYouwillhavetoquitpythonwithquit()tobeabletoreloadit

CommonStudentQuestionsIgetNoneprintedoutforsomeofthefunctionsYouprobablyhaveafunctionthatismissingthereturnattheendGobackwardthroughthefileandconfirmthateverylineisright

Iget-bashimportcommandnotfoundwhenItypeimportex25PayattentiontowhatIrsquomdoingintheWhatYouShouldSeesectionIrsquomdoingthisinPythonnotintheTerminalThatmeansyoufirstrunPython

IgetImportErrorNomodulenamedex25pywhenItypeimportex25pyDonrsquotaddthepytotheendPythonknowsthefileendsinpysoyoujusttypeimportex25

IgetSyntaxErrorinvalidsyntaxwhenIrunthisThatmeansyouhavesomethinglikeamissing(ororsimilarsyntaxerroronthatlineoraboveitAnytimeyougetthaterrorstartatthelineitmentionsandcheckthatitrsquosrightthengobackwardcheckingeachlineabovethat

HowcanthewordspopfunctionchangethewordsvariableThatrsquosacomplicatedquestionbutinthiscasewordsisalistandbecauseofthatyoucangiveitcommandsanditrsquollretaintheresultsofthosecommandsThisissimilartohowfilesandmanyotherthingsworkedwhenyouwereworkingwiththem

WhenshouldIprintinsteadofreturninafunctionThereturnfromafunctiongivesthelineofcodethatcalledthefunctionaresultYoucanthinkofafunctionastakinginputthroughitsargumentsandreturningoutputthroughreturnTheprintiscompletelyunrelatedtothisandonlydealswithprintingoutputtotheTerminal

Exercise26CongratulationsTakeaTest

YouarealmostdonewiththefirsthalfofthebookThesecondhalfiswherethingsgetinterestingYouwilllearnlogicandbeabletodousefulthingslikemakedecisionsBeforeyoucontinueIhaveaquizforyouThisquizwillbeveryhardbecauseitrequiresyoutofixsomeoneelsersquoscodeWhenyouareaprogrammeryouoftenhavetodealwithotherprogrammersrsquocodemdashandalsowiththeirarroganceProgrammerswillveryfrequentlyclaimthattheircodeisperfectTheseprogrammersarestupidpeoplewhocarelittleforothersAgoodprogrammerassumeslikeagoodscientistthattherersquosalwayssomeprobabilitytheircodeiswrongGoodprogrammersstartfromthepremisethattheirsoftwareisbrokenandthenworktoruleoutallpossiblewaysitcouldbewrongbeforefinallyadmittingthatmaybeitreallyistheotherguyrsquoscodeInthisexerciseyouwillpracticedealingwithabadprogrammerbyfixingabadprogrammerrsquoscodeIhavepoorlycopiedExercises24and25intoafileandremovedrandomcharactersandaddedflawsMostoftheerrorsarethingsPythonwilltellyouwhilesomeofthemarematherrorsyoushouldfindOthersareformattingerrorsorspellingmistakesinthestringsAlloftheseerrorsareverycommonmistakesallprogrammersmakemdashevenexperiencedonesYourjobinthisexerciseistocorrectthisfileUseallofyourskillstomakethisfilebetterAnalyzeitfirstmaybeprintingitouttoedititlikeyouwouldaschooltermpaperFixeachflawandkeeprunningitandfixingituntilthescriptrunsperfectlyTrynottogethelpIfyougetstucktakeabreakandcomebacktoitlaterEvenifthistakesdaystodobustthroughitandmakeitrightThepointofthisexerciseisnrsquottotypeitinbuttofixanexistingfileTodothatyoumustgotohttplearnpythonthehardwayorgpython3exercise26txtCopy-pastethecodeintoafilenamedex26pyThisistheonlytimeyouareallowedtocopy-paste

CommonStudentQuestionsDoIhavetoimportex25pyorcanIjustremovethereferencestoitYoucandoeitherThisfilehasthefunctionsfromex25

thoughsofirstgowithremovingreferencestoitCanIrunthecodewhileIrsquomfixingitYoumostcertainlymayThecomputeristheretohelpsouseitasmuchaspossible

Exercise27MemorizingLogic

TodayisthedayyoustartlearningaboutlogicUptothispointyouhavedoneeverythingyoupossiblycanreadingandwritingfilestotheTerminalandhavelearnedquitealotofthemathcapabilitiesofPythonFromnowonyouwillbelearninglogicYouwonrsquotlearncomplextheoriesthatacademicslovetostudybutjustthebasiclogicthatmakesrealprogramsworkandthatrealprogrammersneedeverydayLearninglogichastocomeafteryoudosomememorizationIwantyoutodothisexerciseforanentireweekDonotfalterEvenifyouareboredoutofyourmindkeepdoingitThisexercisehasasetoflogictablesyoumustmemorizetomakeiteasierforyoutodothelaterexercisesIrsquomwarningyouthiswonrsquotbefunatfirstItwillbedownrightboringandtediousbutthisteachesyouaveryimportantskillyouwillneedasaprogrammerYouwillneedtobeabletomemorizeimportantconceptsinyourlifeMostoftheseconceptswillbeexcitingonceyougetthemYouwillstrugglewiththemlikewrestlingasquidthenonedayyouwillunderstanditAllthatworkmemorizingthebasicspaysoffbiglaterHerersquosatiponhowtomemorizesomethingwithoutgoinginsaneDoatinybitatatimethroughoutthedayandmarkdownwhatyouneedtoworkonmostDonottrytositdownfortwohoursstraightandmemorizethesetablesThiswonrsquotworkYourbrainwillonlyretainwhateveryoustudiedinthefirst15or30minutesanywayInsteadcreateabunchofindexcardswitheachcolumnontheleft(TrueorFalse)onthefrontandthecolumnontherightonthebackYoushouldthentakethemoutseetheldquoTrueorFalserdquoandimmediatelysayldquoTruerdquoKeeppracticinguntilyoucandothisOnceyoucandothatstartwritingoutyourowntruthtableseachnightintoanotebookDonotjustcopythemTrytodothemfrommemoryWhenyougetstuckglancequicklyattheonesIhaveheretorefreshyourmemoryDoingthiswilltrainyourbraintorememberthewholetableDonotspendmorethanoneweekonthisbecauseyouwillbeapplyingitasyougo

TheTruthTermsInPythonwehavethefollowingterms(charactersandphrases)fordeterminingifsomethingisldquoTruerdquoorldquoFalserdquoLogiconacomputerisallaboutseeingifsomecombinationofthesecharactersandsomevariablesisTrueatthatpointin

somecombinationofthesecharactersandsomevariablesisTrueatthatpointintheprogram

bullandbullorbullnotbull=(notequal)bull==(equal)bullgt=(greater-than-equal)bulllt=(less-than-equal)bullTruebullFalse

YouactuallyhaverunintothesecharactersbeforebutmaybenotthetermsTheterms(andornot)actuallyworkthewayyouexpectthemtojustlikeinEnglish

TheTruthTablesWewillnowusethesecharacterstomakethetruthtablesyouneedtomemorize

NowusethesetablestowriteupyourowncardsandspendtheweekmemorizingthemRememberthoughthereisnofailinginthisbookjusttryingashardasyoucaneachdayandthenalittlebitmore

CommonStudentQuestionsCanrsquotIjustlearntheconceptsbehindBooleanalgebraandnotmemorizethisSureyoucandothatbutthenyoursquollhavetoconstantlygothroughtherulesforBooleanalgebrawhileyoucodeIfyoumemorizethesefirstitnotonlybuildsyourmemorizationskillsitalsomakestheseoperationsnaturalAfterthattheconceptofBooleanalgebraiseasyButdowhateverworksforyou

Exercise28BooleanPractice

ThelogiccombinationsyoulearnedfromthelastexercisearecalledBooleanlogicexpressionsBooleanlogicisusedeverywhereinprogrammingItisafundamentalpartofcomputationandknowingtheexpressionsisakintoknowingyourscalesinmusicInthisexerciseyouwilltakethelogicexercisesyoumemorizedandstarttryingthemoutinPythonTakeeachoftheselogicproblemsandwritewhatyouthinktheanswerwillbeIneachcaseitwillbeeitherTrueorFalseOnceyouhavetheanswerswrittendownstartPythoninyourTerminalandtypeeachlogicproblemintoconfirmyouranswers

1TrueandTrue2FalseandTrue31==1and2==14test==test51==1or2=16Trueand1==17Falseand0=08Trueor1==19test==testing101=0and2==111test=testing12test==113not(TrueandFalse)14not(1==1and0=1)15not(10==1or1000==1000)16not(1=10or3==4)17not(testing==testingandZed==CoolGuy)

181==1and(not(testing==1or1==0))19chunky==baconand(not(3==4or3==3))203==3and(not(testing==testingor

Python==Fun))

IwillalsogiveyouatricktohelpyoufigureoutthemorecomplicatedonestowardtheendWheneveryouseetheseBooleanlogicstatementsyoucansolvethemeasilybythissimpleprocess1Findanequalitytest(==or=)andreplaceitwithitstruth

2Findeachandorinsideparenthesesandsolvethosefirst3Findeachnotandinvertit4Findanyremainingandorandsolveit5WhenyouaredoneyoushouldhaveTrueorFalse

Iwilldemonstratewithavariationonitem20Clickheretoviewcodeimage

3=4andnot(testing=testorPython==Python)

HerersquosmegoingthrougheachofthestepsandshowingyouthetranslationuntilIrsquoveboileditdowntoasingleresult1Solveeachequalitytest

3=4isTrueTrueandnot(testing=testorPython==Python)

testing=testisTrueTrueandnot(TrueorPython==Python)

Python==PythonTrueandnot(TrueorTrue)2Findeachandorinparentheses()(TrueorTrue)isTrueTrueandnot(True)

3Findeachnotandinvertitnot(True)isFalseTrueandFalse4FindanyremainingandorsandsolvethemTrueandFalseisFalse

WiththatwersquoredoneandknowtheresultisFalse

WarningThemorecomplicatedonesmayseemveryhardatfirstYoushouldbeabletotakeagoodfirststabatsolvingthembutdonotgetdiscouragedIrsquomjustgettingyouprimedformoreoftheseldquologicgymnasticsrdquosothatlatercoolstuffismucheasierJuststickwithitandkeeptrackofwhatyougetwrongbutdonotworrythatitrsquosnotgettinginyourheadquiteyetItrsquollcome

WhatYouShouldSeeAfteryouhavetriedtoguessatthesethisiswhatyoursessionwithPythonmightlooklikeClickheretoviewcodeimage

$python36

Python251(r25154863Feb62009190212)

[GCC401(AppleIncbuild5465)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtTrueandTrue

True

gtgtgt1==1and2==2

True

StudyDrills1TherearealotofoperatorsinPythonsimilarto=and==TrytofindasmanyldquoequalityoperatorsrdquoasyoucanTheyshouldbelikeltorlt=

2WriteoutthenamesofeachoftheseequalityoperatorsForexampleIcall=ldquonotequalrdquo

3PlaywithPythonbytypingoutnewBooleanoperatorsandbeforeyoupressEntertrytoshoutoutwhatitisDonotthinkaboutitShoutthefirstthingthatcomestomindWriteitdownthenpressEnterandkeeptrackofhowmanyyougetrightandwrong

4Throwawaythepieceofpaperfrom3soyoudonotaccidentallytrytouseitlater

CommonStudentQuestionsWhydoestestandtestreturntestor1and1return1insteadofTruePythonandmanylanguagesliketoreturnoneoftheoperandstotheirBooleanexpressionsratherthanjustTrueorFalseThismeansthatifyoudidFalseand1yougetthefirstoperand(False)butifyoudoTrueand1yougetthesecond(1)Playwiththisabit

Isthereanydifferencebetween=andltgtPythonhasdeprecatedltgtinfavorof=souse=Otherthanthatthereshouldbenodifference

IsnrsquotthereashortcutYesAnyandexpressionthathasaFalseisimmediatelyFalsesoyoucanstopthereAnyorexpressionthathasaTrueisimmediatelyTruesoyoucanstopthereButmakesurethatyoucanprocessthewholeexpressionbecauselateritbecomeshelpful

Exercise29WhatIf

HereisthenextscriptofPythonyouwillenterwhichintroducesyoutotheif-statementTypethisinmakeitrunexactlyrightandthenwersquollseeifyourpracticehaspaidoffClickheretoviewcodeimage

ex29py

1people=20

2cats=30

3dogs=15

4

5

6ifpeopleltcats

7print(ToomanycatsTheworldisdoomed)

8

9ifpeoplegtcats

10print(NotmanycatsTheworldissaved)

11

12ifpeopleltdogs

13print(Theworldisdrooledon)

14

15ifpeoplegtdogs

16print(Theworldisdry)

17

18

19dogs+=5

20

21ifpeoplegt=dogs

22print(Peoplearegreaterthanorequaltodogs)

23

24ifpeoplelt=dogs

25print(Peoplearelessthanorequaltodogs)

26

27

28ifpeople==dogs

29print(Peoplearedogs)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise29Session

$python36ex29py

ToomanycatsTheworldisdoomed

Theworldisdry

Peoplearegreaterthanorequaltodogs

Peoplearelessthanorequaltodogs

Peoplearedogs

StudyDrillsInthisStudyDrilltrytoguesswhatyouthinktheif-statementisandwhatitdoesTrytoanswerthesequestionsinyourownwordsbeforemovingontothenextexercise

1Whatdoyouthinktheifdoestothecodeunderit2Whydoesthecodeundertheifneedtobeindentedfourspaces3Whathappensifitisnrsquotindented4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryit

5Whathappensifyouchangetheinitialvaluesforpeoplecatsanddogs

CommonStudentQuestionsWhatdoes+=meanThecodex+=1isthesameasdoingx=x+1butinvolveslesstypingYoucancallthistheldquoincrementbyrdquooperatorThesamegoesfor-=andmanyotherexpressionsyoursquolllearnlater

Exercise30ElseandIf

Inthelastexerciseyouworkedoutsomeif-statementsandthentriedtoguesswhattheyareandhowtheyworkBeforeyoulearnmoreIrsquollexplainwhateverythingisbyansweringthequestionsyouhadfromthepreviousStudyDrillssectionYoudidtheStudyDrillsright

1WhatdoyouthinktheifdoestothecodeunderitAnif-statementcreateswhatiscalledaldquobranchrdquointhecodeItrsquoskindoflikethosechooseyourownadventurebookswhereyouareaskedtoturntoonepageifyoumakeonechoiceandanotherifyougoadifferentdirectionTheif-statementtellsyourscriptldquoIfthisBooleanexpressionisTruethenrunthecodeunderitotherwiseskipitrdquo

2WhydoesthecodeundertheifneedtobeindentedfourspacesAcolonattheendofalineishowyoutellPythonyouaregoingtocreateanewldquoblockrdquoofcodeandthenindentingfourspacestellsPythonwhatlinesofcodeareinthatblockThisisexactlythesamethingyoudidwhenyoumadefunctionsinthefirsthalfofthebook

3WhathappensifitisnrsquotindentedIfitisnrsquotindentedyouwillmostlikelycreateaPythonerrorPythonexpectsyoutoindentsomethingafteryouendalinewitha(colon)

4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryitYesyoucanandtheycanbeascomplexasyoulikealthoughreallycomplexthingsgenerallyarebadstyle

5WhathappensifyouchangetheinitialvaluesforpeoplecatsanddogsBecauseyouarecomparingnumbersifyouchangethenumbersdifferentif-statementswillevaluatetoTrueandtheblocksofcodeunderthemwillrunGobackandputdifferentnumbersinandseeifyoucanfigureoutinyourheadwhichblocksofcodewillrun

ComparemyanswerstoyouranswersandmakesureyoureallyunderstandtheconceptofaldquoblockrdquoofcodeThisisimportantforwhenyoudothenextexercisewhereyouwriteallthepartsofif-statementsthatyoucanuseTypethisoneinandmakeitworktooClickheretoviewcodeimage

ex30py

1people=30

2cars=40

3trucks=15

4

5

6ifcarsgtpeople

7print(Weshouldtakethecars)

8elifcarsltpeople

9print(Weshouldnottakethecars)

10else

11print(Wecantdecide)

12

13iftrucksgtcars

14print(Thatstoomanytrucks)

15eliftrucksltcars

16print(Maybewecouldtakethetrucks)

17else

18print(Westillcantdecide)

19

20ifpeoplegttrucks

21print(Alrightletsjusttakethetrucks)

22else

23print(Fineletsstayhomethen)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise30Session

$python36ex30py

Weshouldtakethecars

Maybewecouldtakethetrucks

Alrightletsjusttakethetrucks

StudyDrills1Trytoguesswhatelifandelsearedoing2Changethenumbersofcarspeopleandtrucksandthentracethrougheachif-statementtoseewhatwillbeprinted

3TrysomemorecomplexBooleanexpressionslikecarsgtpeopleortrucksltcars

4Aboveeachlinewriteacommentdescribingwhatthelinedoes

CommonStudentQuestions

CommonStudentQuestionsWhathappensifmultipleelifblocksareTruePythonstartsatthetopandrunsthefirstblockthatisTruesoitwillrunonlythefirstone

Exercise31MakingDecisions

InthefirsthalfofthisbookyoumostlyjustprintedoutstringsandcalledfunctionsbuteverythingwasbasicallyinastraightlineYourscriptsranstartingatthetopandwenttothebottomwheretheyendedIfyoumadeafunctionyoucouldrunthatfunctionlaterbutitstilldidnrsquothavethekindofbranchingyouneedtoreallymakedecisionsNowthatyouhaveifelseandelifyoucanstarttomakescriptsthatdecidethingsInthelastscriptyouwroteoutasimplesetoftestsaskingsomequestionsInthisscriptyouwillasktheuserquestionsandmakedecisionsbasedontheiranswersWritethisscriptandthenplaywithitquitealottofigureitoutClickheretoviewcodeimage

ex31py

1print(Youenteradarkroomwithtwodoors

2Doyougothroughdoor1ordoor2)

3

4door=input(gt)

5

6ifdoor==1

7print(Theresagiantbearhereeatingacheesecake)

8print(Whatdoyoudo)

9print(1Takethecake)

10print(2Screamatthebear)

11

12bear=input(gt)

13

14ifbear==1

15print(ThebeareatsyourfaceoffGoodjob)

16elifbear==2

17print(ThebeareatsyourlegsoffGoodjob)

18else

19print(fWelldoingbearisprobablybetter)

20print(Bearrunsaway)

21

22elifdoor==2

23print(YoustareintotheendlessabyssatCthulhus

retina)

24print(1Blueberries)

25print(2Yellowjacketclothespins)

26print(3Understandingrevolversyellingmelodies)

27

28insanity=input(gt)

29

30ifinsanity==1orinsanity==2

31print(Yourbodysurvivespoweredbyamindofjello)

32print(Goodjob)

33else

34print(Theinsanityrotsyoureyesintoapoolof

muck)

35print(Goodjob)

36

37else

38print(YoustumblearoundandfallonaknifeanddieGood

job)Akeypointhereisthatyouarenowputtingtheif-statements

insideif-statementsascodethatcanrunThisisverypowerfuland

canbeusedtocreateldquonestedrdquodecisionswhereonebranchleadsto

anotherandanother

Makesureyouunderstandthisconceptofif-statementsinsideif-statementsInfactdotheStudyDrillstoreallynailit

WhatYouShouldSeeHereismeplayingthislittleadventuregameIdonotdosowellClickheretoviewcodeimage

Exercise31Session

$python36ex31py

Youenteradarkroomwithtwodoors

Doyougothroughdoor1ordoor2

gt1

Theresagiantbearhereeatingacheesecake

Whatdoyoudo

1Takethecake

2Screamatthebear

gt2

ThebeareatsyourlegsoffGoodjob

StudyDrills1MakenewpartsofthegameandchangewhatdecisionspeoplecanmakeExpandthegameoutasmuchasyoucanbeforeitgetsridiculous

2WriteacompletelynewgameMaybeyoudonrsquotlikethisonesomakeyourownThisisyourcomputerdowhatyouwant

CommonStudentQuestions

CommonStudentQuestionsCanyoureplaceelifwithasequenceofif-elsecombinationsYoucaninsomesituationsbutitdependsonhoweachifelseiswrittenItalsomeansthatPythonwillcheckeveryif-elsecombinationratherthanjustthefirstfalseoneslikeitwouldwithif-elif-elseTrytomakesomeofthesetofigureoutthedifferences

HowdoItellwhetheranumberisbetweenarangeofnumbersYouhavetwooptionsUse0ltxlt10or1lt=xlt10whichisclassicnotationorusexinrange(110)

WhatifIwantedmoreoptionsintheif-elif-elseblocksAddmoreelifblocksforeachpossiblechoice

Exercise32LoopsandLists

YoushouldnowbeabletodosomeprogramsthataremuchmoreinterestingIfyouhavebeenkeepingupyoushouldrealizethatnowyoucancombinealltheotherthingsyouhavelearnedwithif-statementsandBooleanexpressionstomakeyourprogramsdosmartthingsHoweverprogramsalsoneedtodorepetitivethingsveryquicklyWearegoingtouseafor-loopinthisexercisetobuildandprintvariouslistsWhenyoudotheexerciseyouwillstarttofigureoutwhattheyareIwonrsquottellyourightnowYouhavetofigureitoutBeforeyoucanuseafor-loopyouneedawaytostoretheresultsofloopssomewhereThebestwaytodothisiswithlistsAlistisexactlywhatthenamesaysacontainerofthingsthatareorganizedinorderfromfirsttolastItrsquosnotcomplicatedyoujusthavetolearnanewsyntaxFirstherersquoshowyoumakelistsClickheretoviewcodeimage

hairs=[brownblondred]

eyes=[brownbluegreen]

weights=[1234]

Youstartthelistwiththe[(leftbracket)whichldquoopensrdquothelistThenyouputeachitemyouwantinthelistseparatedbycommassimilartofunctionargumentsLastlyendthelistwitha](rightbracket)toindicatethatitrsquosoverPythonthentakesthislistandallitscontentsandassignsthemtothevariable

WarningThisiswherethingsgettrickyforpeoplewhocanrsquotcodeYourbrainhasbeentaughtthattheworldisflatRememberinthelastexercisewhereyouputif-statementsinsideif-statementsThatprobablymadeyourbrainhurtbecausemostpeopledonotponderhowtoldquonestrdquothingsinsidethingsInprogrammingnestedstructuresareallovertheplaceYouwillfindfunctionsthatcallotherfunctionsthathaveif-statementsthathavelistswithlistsinsidelistsIfyouseeastructurelikethisthatyoucanrsquotfigureouttakeoutapencilandpaperandbreakitdownmanuallybitbybituntilyouunderstandit

Wenowwillbuildsomelistsusingsomefor-loopsandprintthemoutClickheretoviewcodeimage

ex32py

1the_count=[12345]

2fruits=[applesorangespearsapricots]

3change=[1pennies2dimes3quarters]

4

5thisfirstkindoffor-loopgoesthroughalist

6fornumberinthe_count

7print(fThisiscountnumber)

8

9sameasabove

10forfruitinfruits

11print(fAfruitoftypefruit)

12

13alsowecangothroughmixedliststoo

14noticewehavetousesincewedontknowwhatsinit

15foriinchange

16print(fIgoti)

17

18wecanalsobuildlistsfirststartwithanemptyone

19elements=[]

20

21thenusetherangefunctiontodo0to5counts

22foriinrange(06)

23print(fAddingitothelist)

24appendisafunctionthatlistsunderstand

25elementsappend(i)

26

27nowwecanprintthemouttoo

28foriinelements

29print(fElementwasi)

WhatYouShouldSee

Exercise32Session

$python36ex32py

Thisiscount1

Thisiscount2

Thisiscount3

Thisiscount4

Thisiscount5

Afruitoftypeapples

Afruitoftypeoranges

Afruitoftypepears

Afruitoftypeapricots

Igot1

Igotpennies

Igot2

Igotdimes

Igot3

Igotquarters

Adding0tothelist

Adding1tothelist

Adding2tothelist

Adding3tothelist

Adding4tothelist

Adding5tothelist

Elementwas0

Elementwas1

Elementwas2

Elementwas3

Elementwas4

Elementwas5

StudyDrills1TakealookathowyouusedrangeLookuptherangefunctiontounderstandit

2Couldyouhaveavoidedthatfor-loopentirelyonline22andjustassignedrange(06)directlytoelements

3FindthePythondocumentationonlistsandreadaboutthemWhatotheroperationscanyoudotolistsbesidesappend

CommonStudentQuestionsHowdoyoumakea2-dimensional(2D)listThatrsquosalistinalistlikethis[[123][456]]

ArenrsquotlistsandarraysthesamethingThatdependsonthelanguageandtheimplementationInclassictermsalistisverydifferentfromanarraybecauseofhowtheyrsquoreimplementedInRubythoughtheycallthesearraysInPythontheycallthemlistsJustcalltheselistsfornowsincethatrsquoswhatPythoncallsthem

Whyisafor-loopabletouseavariablethatisnrsquotdefinedyetThevariableisdefinedbythefor-loopwhenitstartsinitializingittothecurrentelementoftheloopiterationeachtimethrough

Whydoesforiinrange(13)onlylooptwotimesinsteadofthreetimesTherange()functiononlydoesnumbersfromthefirsttothelastnotincludingthelastSoitstopsattwonotthreeintheprecedingThisturnsouttobethemostcommonwaytodothiskindofloop

Whatdoeselementsappend()doItsimplyappendstotheendofthelistOpenupthePythonshellandtryafewexampleswithalistyoumakeAnytimeyourunintothingslikethisalwaystrytoplaywiththeminteractivelyinthePythonshell

Exercise33WhileLoops

Nowtototallyblowyourmindwithanewloopthewhile-loopAwhile-loopwillkeepexecutingthecodeblockunderitaslongasaBooleanexpressionisTrueWaityouhavebeenkeepingupwiththeterminologyrightThatifwewritealineandenditwitha(colon)thenthattellsPythontostartanewblockofcodeThenweindentandthatrsquosthenewcodeThisisallaboutstructuringyourprogramssothatPythonknowswhatyoumeanIfyoudonotgetthatideathengobackanddosomemoreworkwithif-statementsfunctionsandthefor-loopuntilyougetitLateronwersquollhavesomeexercisesthatwilltrainyourbraintoreadthesestructuressimilartohowweburnedBooleanexpressionsintoyourbrainBacktowhile-loopsWhattheydoissimplydoatestlikeanif-statementbutinsteadofrunningthecodeblockoncetheyjumpbacktotheldquotoprdquowherethewhileisandrepeatAwhile-looprunsuntiltheexpressionisFalseHerersquostheproblemwithwhile-loopsSometimestheydonotstopThisisgreatifyourintentionistojustkeeploopinguntiltheendoftheuniverseOtherwiseyoualmostalwayswantyourloopstoendeventuallyToavoidtheseproblemstherearesomerulestofollow1Makesurethatyouusewhile-loopssparinglyUsuallyafor-loopisbetter

2ReviewyourwhilestatementsandmakesurethattheBooleantestwillbecomeFalseatsomepoint

3Whenindoubtprintoutyourtestvariableatthetopandbottomofthewhile-looptoseewhatitrsquosdoing

Inthisexerciseyoulearnthewhile-loopwhiledoingthesethreechecksClickheretoviewcodeimage

ex33py

1i=0

2numbers=[]

3

4whileilt6

5print(fAtthetopiisi)

6numbersappend(i)

7

8i=i+1

9print(Numbersnownumbers)

10print(fAtthebottomiisi)

11

12

13print(Thenumbers)

14

15fornuminnumbers

16print(num)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise33Session

$python36ex33py

Atthetopiis0

Numbersnow[0]

Atthebottomiis1

Atthetopiis1

Numbersnow[01]

Atthebottomiis2

Atthetopiis2

Numbersnow[012]

Atthebottomiis3

Atthetopiis3

Numbersnow[0123]

Atthebottomiis4

Atthetopiis4

Numbersnow[01234]

Atthebottomiis5

Atthetopiis5

Numbersnow[012345]

Atthebottomiis6

Thenumbers

0

1

2

3

4

5

StudyDrills

1Convertthiswhile-looptoafunctionthatyoucancallandreplace6inthetest(ilt6)withavariable

2Usethisfunctiontorewritethescripttotrydifferentnumbers3Addanothervariabletothefunctionargumentsthatyoucanpassinthatletsyouchangethe+1online8soyoucanchangehowmuchitincrementsby

4Rewritethescriptagaintousethisfunctiontoseewhateffectthathas5Writeittousefor-loopsandrangeDoyouneedtheincrementorinthemiddleanymoreWhathappensifyoudonotgetridofit

Ifatanytimeyouaredoingthisitgoescrazy(itprobablywill)justholddownCTRLandpressc(CTRL-c)andtheprogramwillabort

CommonStudentQuestionsWhatrsquosthedifferencebetweenafor-loopandawhile-loopAfor-loopcanonlyiterate(loop)ldquooverrdquocollectionsofthingsAwhile-loopcandoanykindofiteration(looping)youwantHoweverwhile-loopsarehardertogetrightandyounormallycangetmanythingsdonewithfor-loops

LoopsarehardHowdoIfigurethemoutThemainreasonpeopledonrsquotunderstandloopsisbecausetheycanrsquotfollowtheldquojumpingrdquothatthecodedoesWhenalooprunsitgoesthroughitsblockofcodeandattheenditjumpsbacktothetopTovisualizethisputprintstatementsallovertheloopprintingoutwhereintheloopPythonisrunningandwhatthevariablesaresettoatthosepointsWriteprintlinesbeforetheloopatthetopoftheloopinthemiddleandatthebottomStudytheoutputandtrytounderstandthejumpingthatrsquosgoingon

Exercise34AccessingElementsofLists

ListsareprettyusefulbutunlessyoucangetatthethingsinthemtheyarenrsquotallthatgoodYoucanalreadygothroughtheelementsofalistinorderbutwhatifyouwantsaythefifthelementYouneedtoknowhowtoaccesstheelementsofalistHerersquoshowyouwouldaccessthefirstelementofalistClickheretoviewcodeimage

animals=[beartigerpenguinzebra]

bear=animals[0]

Youtakealistofanimalsandthenyougetthefirst(1st)oneusing0HowdoesthatworkBecauseofthewaymathworksPythonstartsitslistsat0ratherthan1ItseemsweirdbuttherearemanyadvantagestothiseventhoughitismostlyarbitraryThebestwaytoexplainwhyisbyshowingyouthedifferencebetweenhowyouusenumbersandhowprogrammersusenumbersImagineyouarewatchingthefouranimalsinourlist([beartigerpenguinzebra])runinaraceTheycrossthefinishlineintheorderwehavetheminthislistTheracewasreallyexcitingbecausetheanimalsdidnrsquoteateachotherandsomehowmanagedtorunaraceYourfriendshowsuplateandwantstoknowwhowonDoesyourfriendsayldquoHeywhocameinzerothrdquoNohesaysldquoHeywhocameinfirstrdquoThisisbecausetheorderoftheanimalsisimportantYoucanrsquothavethesecondanimalwithoutthefirst(1st)animalandyoucanrsquothavethethirdwithoutthesecondItrsquosalsoimpossibletohavealdquozerothrdquoanimalsincezeromeansnothingHowcanyouhaveanothingwinaraceItjustdoesnrsquotmakesenseWecallthesekindsofnumbersldquoordinalrdquonumbersbecausetheyindicateanorderingofthingsProgrammershowevercanrsquotthinkthiswaybecausetheycanpickanyelementoutofalistatanypointToprogrammersthelistofanimalsismorelikeadeckofcardsIftheywantthetigertheygrabitIftheywantthezebratheycantakeittooThisneedtopullelementsoutoflistsatrandommeansthattheyneedawaytoindicateelementsconsistentlybyanaddressoranldquoindexrdquoandthebestwaytodothatistostarttheindicesat0TrustmeonthisthemathiswayeasierforthesekindsofaccessesThiskindofnumberisaldquocardinalrdquonumberandmeansyoucanpickatrandomsothereneedstobea0elementHowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourself

HowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourselfldquoIwantthethirdanimalrdquoyoutranslatethisldquoordinalrdquonumbertoaldquocardinalrdquonumberbysubtracting1Theldquothirdrdquoanimalisatindex2andisthepenguinYouhavetodothisbecauseyouhavespentyourwholelifeusingordinalnumbersandnowyouhavetothinkincardinalJustsubtract1andyoursquoregoodRememberordinal==ordered1stcardinal==cardsatrandom0LetrsquospracticethisTakethislistofanimalsandfollowtheexerciseswhereItellyoutowritedownwhatanimalyougetforthatordinalorcardinalnumberRememberifIsayldquofirstrdquoldquosecondrdquothenIrsquomusingordinalsosubtract1IfIgiveyoucardinal(likeldquoTheanimalat1rdquo)thenuseitdirectlyClickheretoviewcodeimage

animals=[bearpython36peacockkangaroowhale

platypus]

1Theanimalat12Thethird(3rd)animal3Thefirst(1st)animal4Theanimalat35Thefifth(5th)animal6Theanimalat27Thesixth(6th)animal8Theanimalat4

ForeachofthesewriteoutafullsentenceoftheformldquoThefirst(1st)animalisat0andisabearrdquoThensayitbackwardsldquoTheanimalat0isthe1stanimalandisabearrdquoUseyourPythontocheckyouranswers

StudyDrills1Withwhatyouknowofthedifferencebetweenthesetypesofnumberscanyouexplainwhytheyear2010inldquoJanuary12010rdquoreallyis2010andnot2009(Hintyoucanrsquotpickyearsatrandom)

2Writesomemorelistsandworkoutsimilarindexesuntilyoucantranslatethem

3UsePythontocheckyouranswers

Warning

ProgrammerswilltellyoutoreadthisguynamedDijkstraonthissubjectIrecommendyouavoidhiswritingsonthisunlessyouenjoybeingyelledatbysomeonewhostoppedprogrammingatthesametimeprogrammingstarted

Exercise35BranchesandFunctions

Youhavelearnedif-statementsfunctionsandlistsNowitrsquostimetobendyourmindTypethisinandseeifyoucanfigureoutwhatitrsquosdoingClickheretoviewcodeimage

ex35py

1fromsysimportexit

2

3defgold_room()

4print(ThisroomisfullofgoldHowmuchdoyoutake)

5

6choice=input(gt)

7if0inchoiceor1inchoice

8how_much=int(choice)

9else

10dead(Manlearntotypeanumber)

11

12ifhow_muchlt50

13print(Niceyourenotgreedyyouwin)

14exit(0)

15else

16dead(Yougreedybastard)

17

18

19defbear_room()

20print(Thereisabearhere)

21print(Thebearhasabunchofhoney)

22print(Thefatbearisinfrontofanotherdoor)

23print(Howareyougoingtomovethebear)

24bear_moved=False

25

26whileTrue

27choice=input(gt)

28

29ifchoice==takehoney

30dead(Thebearlooksatyouthenslapsyourface

off)

31elifchoice==tauntbearandnotbear_moved

32print(Thebearhasmovedfromthedoor)

33print(Youcangothroughitnow)

34bear_moved=True

35elifchoice==tauntbearandbear_moved

36dead(Thebeargetspissedoffandchewsyourleg

off)

37elifchoice==opendoorandbear_moved

38gold_room()

39else

40print(Igotnoideawhatthatmeans)

41

42

43defcthulhu_room()

44print(HereyouseethegreatevilCthulhu)

45print(Heitwhateverstaresatyouandyougoinsane)

46print(Doyoufleeforyourlifeoreatyourhead)

47

48choice=input(gt)

49

50iffleeinchoice

51start()

52elifheadinchoice

53dead(Wellthatwastasty)

54else

55cthulhu_room()

56

57

58defdead(why)

59print(whyGoodjob)

60exit(0)

61

62defstart()

63print(Youareinadarkroom)

64print(Thereisadoortoyourrightandleft)

65print(Whichonedoyoutake)

66

67choice=input(gt)

68

69ifchoice==left

70bear_room()

71elifchoice==right

72cthulhu_room()

73else

74dead(Youstumblearoundtheroomuntilyoustarve)

75

76

77start()

WhatYouShouldSeeHerersquosmeplayingthegameClickheretoviewcodeimage

Exercise35Session

$python36ex35py

Youareinadarkroom

Thereisadoortoyourrightandleft

Whichonedoyoutake

gtleft

Thereisabearhere

Thebearhasabunchofhoney

Thefatbearisinfrontofanotherdoor

Howareyougoingtomovethebear

gttauntbear

Thebearhasmovedfromthedoor

Youcangothroughitnow

gtopendoor

ThisroomisfullofgoldHowmuchdoyoutake

gt1000

YougreedybastardGoodjob

StudyDrills1Drawamapofthegameandhowyouflowthroughit2Fixallofyourmistakesincludingspellingmistakes3Writecommentsforthefunctionsyoudonotunderstand4AddmoretothegameWhatcanyoudotobothsimplifyandexpandit5Thegold_roomhasaweirdwayofgettingyoutotypeanumberWhatareallthebugsinthiswayofdoingitCanyoumakeitbetterthanwhatIrsquovewrittenLookathowint()worksforclues

CommonStudentQuestionsHelpHowdoesthisprogramworkWhenyougetstuckunderstandingapieceofcodesimplywriteanEnglishcommentaboveeverylineexplainingwhatthatlinedoesKeepyourcommentsshortandsimilartothecodeTheneitherdiagramhowthecodeworksorwriteaparagraphdescribingitIfyoudothatyoursquollgetit

WhydidyouwritewhileTrueThatmakesaninfiniteloopWhatdoesexit(0)doOnmanyoperatingsystemsaprogramcanabortwithexit(0)andthenumberpassedinwillindicateanerrorornotIfyoudoexit(1)thenitwillbeanerrorbutexit(0)willbeagoodexitThereasonitrsquosbackwardfromnormalBooleanlogic(with0==False)isthatyoucanusedifferentnumbersto

indicatedifferenterrorresultsYoucandoexit(100)foradifferenterrorresultthanexit(2)orexit(1)

Whyisinput()sometimeswrittenasinput(gt)Theparametertoinputisastringthatitshouldprintasapromptbeforegettingtheuserrsquosinput

Exercise36DesigningandDebugging

Nowthatyouknowif-statementsIrsquomgoingtogiveyousomerulesforfor-loopsandwhile-loopsthatwillkeepyououtoftroubleIrsquomalsogoingtogiveyousometipsondebuggingsothatyoucanfigureoutproblemswithyourprogramFinallyyouwilldesignalittlegamesimilartothelastexercisebutwithaslighttwist

Rulesforif-statements1Everyif-statementmusthaveanelse2IfthiselseshouldneverrunbecauseitdoesnrsquotmakesensethenyoumustuseadiefunctionintheelsethatprintsoutanerrormessageanddiesjustlikewedidinthelastexerciseThiswillfindmanyerrors

3Nevernestif-statementsmorethantwodeepandalwaystrytodothemonedeep

4Treatif-statementslikeparagraphswhereeachif-elif-elsegroupingislikeasetofsentencesPutblanklinesbeforeandafter

5YourBooleantestsshouldbesimpleIftheyarecomplexmovetheircalculationstovariablesearlierinyourfunctionanduseagoodnameforthevariable

IfyoufollowthesesimplerulesyouwillstartwritingbettercodethanmostprogrammersGobacktothelastexerciseandseeifIfollowedalloftheserulesIfnotfixmymistakes

WarningNeverbeaslavetotherulesinreallifeFortrainingpurposesyouneedtofollowtheserulestomakeyourmindstrongbutinreallifesometimestheserulesarejuststupidIfyouthinkaruleisstupidtrynotusingit

RulesforLoops1Useawhile-looponlytoloopforeverandthatmeansprobablyneverThisonlyappliestoPythonotherlanguagesaredifferent

2Useafor-loopforallotherkindsofloopingespeciallyifthereisa

fixedorlimitednumberofthingstoloopover

TipsforDebugging1DonotusealdquodebuggerrdquoAdebuggerislikedoingafull-bodyscanonasickpersonYoudonotgetanyspecificusefulinformationandyoufindawholelotofinformationthatdoesnrsquothelpandisjustconfusing

2Thebestwaytodebugaprogramistouseprinttoprintoutthevaluesofvariablesatpointsintheprogramtoseewheretheygowrong

3MakesurepartsofyourprogramsworkasyouworkonthemDonotwritemassivefilesofcodebeforeyoutrytorunthemCodealittlerunalittlefixalittle

HomeworkNowwriteagamesimilartotheonethatIcreatedinthelastexerciseItcanbeanykindofgameyouwantinthesameflavorSpendaweekonitmakingitasinterestingaspossibleForStudyDrillsuselistsfunctionsandmodules(rememberthosefromExercise13)asmuchaspossibleandfindasmanynewpiecesofPythonasyoucantomakethegameworkBeforeyoustartcodingyoumustdrawamapforyourgameCreatetheroomsmonstersandtrapsthattheplayermustgothroughonpaperbeforeyoucodeOnceyouhaveyourmaptrytocodeitupIfyoufindproblemswiththemapthenadjustitandmakethecodematchThebestwaytoworkonapieceofsoftwareisinsmallchunkslikethis

1OnasheetofpaperoranindexcardwritealistoftasksyouneedtocompletetofinishthesoftwareThisisyourto-dolist

2Picktheeasiestthingyoucandofromyourlist3WriteoutEnglishcommentsinyoursourcefileasaguideforhowyouwouldaccomplishthistaskinyourcode

4WritesomeofthecodeundertheEnglishcomments5Quicklyrunyourscriptsoseeifthatcodeworked6Keepworkinginacycleofwritingsomecoderunningittotestitandfixingituntilitworks

7CrossthistaskoffyourlistthenpickyournexteasiesttaskandrepeatThisprocesswillhelpyouworkonsoftwareinamethodicalandconsistentmannerAsyouworkupdateyourlistbyremovingtasksyoudonrsquotreallyneedandaddingonesyoudo

andaddingonesyoudo

Exercise37SymbolReview

ItrsquostimetoreviewthesymbolsandPythonwordsyouknowandpickupafewmoreforthenextfewlessonsIhavewrittenoutallthePythonsymbolsandkeywordsthatareimportanttoknowInthislessontakeeachkeywordandfirsttrytowriteoutwhatitdoesfrommemoryNextsearchonlineforitandseewhatitreallydoesThismaybedifficultbecausesomeofthesearedifficulttosearchforbuttryanywayIfyougetoneofthesewrongfrommemorymakeanindexcardwiththecorrectdefinitionandtrytoldquocorrectrdquoyourmemoryFinallyuseeachoftheseinasmallPythonprogramorasmanyasyoucangetdoneThegoalistofindoutwhatthesymboldoesmakesureyougotitrightcorrectitifyoudidnotthenuseittolockitin

Keywords

DataTypesFordatatypeswriteoutwhatmakesupeachoneForexamplewithstringswriteouthowyoucreateastringFornumberswriteoutafewnumbers

StringEscapeSequencesForstringescapesequencesusetheminstringstomakesuretheydowhatyouthinktheydo

OldStyleStringFormatsSamethingforstringformatsusetheminsomestringstoknowwhattheydoOlderPython2codeusestheseformattingcharacterstodowhatf-stringsdoTrythemoutasanalternative

OperatorsSomeofthesemaybeunfamiliartoyoubutlookthemupanywayFindoutwhattheydoandifyoustillcanrsquotfigureitoutsaveitforlater

SpendaboutaweekonthisbutifyoufinishfasterthatrsquosgreatThepointistotrytogetcoverageonallthesesymbolsandmakesuretheyarelockedinyourheadWhatrsquosalsoimportantistofindoutwhatyoudonotknowsoyoucanfixitlater

ReadingCodeNowfindsomePythoncodetoreadYoushouldbereadinganyPythoncodeyoucanandtryingtostealideasthatyoufindYouactuallyshouldhaveenoughknowledgetobeabletoreadbutmaybenotunderstandwhatthecodedoesWhatthislessonteachesishowtoapplythingsyouhavelearnedtounderstandotherpeoplersquoscodeFirstprintoutthecodeyouwanttounderstandYesprintitoutbecauseyoureyesandbrainaremoreusedtoreadingpaperthancomputerscreensMakesureyouprintafewpagesatatimeSecondgothroughyourprintoutandtakenotesonthefollowing

1Functionsandwhattheydo2Whereeachvariableisfirstgivenavalue3AnyvariableswiththesamenamesindifferentpartsoftheprogramThesemaybetroublelater

4Anyif-statementswithoutelseclausesAretheyright5Anywhile-loopsthatmightnotend6Anypartsofcodethatyoucanrsquotunderstandforwhateverreason

ThirdonceyouhaveallofthismarkeduptrytoexplainittoyourselfbywritingcommentsasyougoExplainthefunctionshowtheyareusedwhatvariablesareinvolvedandanythingyoucantofigurethiscodeoutLastonallofthedifficultpartstracethevaluesofeachvariablelinebylinefunctionbyfunctionInfactdoanotherprintoutandwriteinthemarginthevalueofeachvariablethatyouneedtoldquotracerdquoOnceyouhaveagoodideaofwhatthecodedoesgobacktothecomputerandreaditagaintoseeifyoufindnewthingsKeepfindingmorecodeanddoingthisuntilyoudonotneedtheprintoutsanymore

StudyDrills1Findoutwhataldquoflowchartrdquoisanddrawafew2Ifyoufinderrorsincodeyouarereadingtrytofixthemandsendtheauthoryourchanges

3AnothertechniqueforwhenyouarenotusingpaperistoputcommentswithyournotesinthecodeSometimesthesecouldbecometheactualcommentstohelpthenextperson

CommonStudentQuestionsHowwouldIsearchforthesethingsonlineSimplyputldquopython36rdquobeforeanythingyouwanttofindForexampletofindldquoyieldrdquosearchforldquopython36yieldrdquo

Exercise38DoingThingstoLists

YouhavelearnedaboutlistsWhenyoulearnedaboutwhile-loopsyouldquoappendedrdquonumberstotheendofalistandprintedthemoutTherewerealsoStudyDrillswhereyouweresupposedtofindalltheotherthingsyoucandotolistsinthePythondocumentationThatwasawhilebacksoreviewthosetopicsifyoudonotknowwhatIrsquomtalkingaboutFounditRememberitGoodWhenyoudidthisyouhadalistandyouldquocalledrdquothefunctionappendonitHoweveryoumaynotreallyunderstandwhatrsquosgoingonsoletrsquosseewhatwecandotolistsWhenyouwritemystuffappend(hello)youareactuallysettingoffachainofeventsinsidePythontocausesomethingtohappentothemystufflistHerersquoshowitworks1PythonseesyoumentionedmystuffandlooksupthatvariableItmighthavetolookbackwardtoseeifyoucreateditwith=ifitisafunctionargumentorifitrsquosaglobalvariableEitherwayithastofindmystufffirst

2Onceitfindsmystuffitreadsthe(period)operatorandstartstolookatvariablesthatareapartofmystuffSincemystuffisalistitknowsthatmystuffhasabunchoffunctions

3ItthenhitsappendandcomparesthenametoallthenamesthatmystuffsaysitownsIfappendisinthere(itis)thenPythongrabsthattouse

4NextPythonseesthe((openparenthesis)andrealizesldquoOhheythisshouldbeafunctionrdquoAtthispointitcalls(runsorexecutes)thefunctionjustlikenormalbutitcallsthefunctionwithanextraargument

5ThatextraargumentismystuffIknowweirdrightButthatrsquoshowPythonworkssoitrsquosbesttojustrememberitandassumethatrsquostheresultWhathappensattheendofallthisisafunctioncallthatlookslikeappend(mystuffhello)insteadofwhatyoureadwhichismystuffappend(hello)

ForthemostpartyoudonothavetoknowthatthisisgoingonbutithelpswhenyougeterrormessagesfromPythonlikethisClickheretoviewcodeimage

$python36

gtgtgtclassThing(object)

deftest(message)

print(message)

gtgtgta=Thing()

gtgtgtatest(hello)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

TypeErrortest()takesexactly1argument(2given)

gtgtgtWhatwasallthatWellthisismetypingintothePythonshell

andshowingyousomemagicYouhavenrsquotseenclassyetbutwersquollget

intothatlaterFornowyouseehowPythonsaidtest()takesexactly

1argument(2given)IfyouseethisitmeansthatPythonchanged

atest(hello)totest(ahello)andthatsomewheresomeonemessed

upanddidnrsquotaddtheargumentfora

ThismightbealottotakeinbutwersquoregoingtospendafewexercisesgettingthisconceptfirminyourbrainTokickthingsoffherersquosanexercisethatmixesstringsandlistsforallkindsoffunClickheretoviewcodeimage

ex38py

1ten_things=ApplesOrangesCrowsTelephoneLightSugar

2

3print(Waittherearenot10thingsinthatlistLetsfix

that)

4

5stuff=ten_thingssplit()

6more_stuff=[DayNightSongFrisbee

7CornBananaGirlBoy]

8

9whilelen(stuff)=10

10next_one=more_stuffpop()

11print(Addingnext_one)

12stuffappend(next_one)

13print(fTherearelen(stuff)itemsnow)

14

15print(Therewegostuff)

16

17print(Letsdosomethingswithstuff)

18

19print(stuff[1])

20print(stuff[-1])whoafancy

21print(stuffpop())

22print(join(stuff))whatcool

23print(join(stuff[35]))superstellar

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Waittherearenot10thingsinthatlistLetsfixthat

AddingBoy

Thereare7itemsnow

AddingGirl

Thereare8itemsnow

AddingBanana

Thereare9itemsnow

AddingCorn

Thereare10itemsnow

Therewego[ApplesOrangesCrowsTelephoneLight

SugarBoyGirlBananaCorn]

Letsdosomethingswithstuff

Oranges

Corn

Corn

ApplesOrangesCrowsTelephoneLightSugarBoyGirlBanana

TelephoneLight

WhatListsCanDoLetrsquossayyouwanttocreateacomputergamebasedonGoFishIfyoudonrsquotknowwhatGoFishistakethetimenowtogoreaduponitontheinternetTodothisyouwouldneedtohavesomewayoftakingtheconceptofaldquodeckofcardsrdquoandputtingitintoyourPythonprogramYouthenhavetowritePythoncodethatknowshowtoworkthisimaginaryversionofadeckofcardssothatapersonplayingyourgamethinksthatitrsquosrealevenifitisnrsquotWhatyouneedisaldquodeckofcardsrdquostructureandprogrammerscallthiskindofthingadatastructureWhatrsquosadatastructureIfyouthinkaboutitadatastructureisjustaformalwaytostructure(organize)somedata(facts)ItreallyisthatsimpleEventhoughsomedatastructurescangetinsanelycomplexalltheyareisjustawaytostorefactsinsideaprogramsoyoucanaccessthemindifferentwaysTheystructuredataIrsquollbegettingintothismoreinthenextexercisebutlistsareoneofthemostcommondatastructuresprogrammersuseAlistisanorderedlistofthingsyouwanttostoreandaccessrandomlyorlinearlybyanindexWhatRememberwhatIsaidthoughjustbecauseaprogrammersaidldquolistisalistrdquodoesnrsquotmeanthatitrsquosanymorecomplexthanwhatalistalreadyisintherealworldLetrsquoslookatthedeckofcardsasanexampleofalist1Youhaveabunchofcardswithvalues

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard3Youcantakecardsoffthetopthebottomorthemiddleatrandom4Ifyouwanttofindaspecificcardyouhavetograbthedeckandgothroughitoneatatime

LetrsquoslookatwhatIsaidldquoAnorderedlistrdquoYesdeckofcardsisinorderwithafirstandalast

ldquoofthingsyouwanttostorerdquoYescardsarethingsIwanttostoreldquoandaccessrandomlyrdquoYesIcangrabacardfromanywhereinthedeck

ldquoorlinearlyrdquoYesifIwanttofindaspecificcardIcanstartatthebeginningandgoinorder

ldquobyanindexrdquoAlmostsincewithadeckofcardsifItoldyoutogetthecardatindex19yoursquodhavetocountuntilyoufoundthatoneInourPythonliststhecomputercanjustjumprighttoanyindexyougiveit

ThatisallalistdoesandthisshouldgiveyouawaytofigureoutconceptsinprogrammingEveryconceptinprogrammingusuallyhassomerelationshiptotherealworldAtleasttheusefulonesdoIfyoucanfigureoutwhattheanalogintherealworldisthenyoucanusethattofigureoutwhatthedatastructureshouldbeabletodo

WhentoUseListsYouusealistwheneveryouhavesomethingthatmatchesthelistdatastructurersquosusefulfeatures

1IfyouneedtomaintainorderRememberthisislistedordernotsortedorderListsdonotsortforyou

2IfyouneedtoaccessthecontentsrandomlybyanumberRememberthisisusingcardinalnumbersstartingat0

3Ifyouneedtogothroughthecontentslinearly(firsttolast)Rememberthatrsquoswhatfor-loopsarefor

Thisiswhenyouusealist

StudyDrills1TakeeachfunctionthatiscalledandgothroughthestepsforfunctioncallstotranslatethemtowhatPythondoesForexamplemore_stuffpop()ispop(more_stuff)

2TranslatethesetwowaystoviewthefunctioncallsinEnglishForexamplemore_stuffpop()readsasldquoCallpoponmore_stuffrdquoMeanwhilepop(more_stuff)meansldquoCallpopwithargumentmore_stuffrdquoUnderstandhowtheyarereallythesamething

3Goreadaboutobject-orientedprogrammingonlineConfusedIwastooDonotworryYouwilllearnenoughtobedangerousandyoucanslowlylearnmorelater

4ReaduponwhataclassisinPythonDonotreadabouthowotherlanguagesusethewordldquoclassrdquoThatwillonlymessyouup

5DonotworryIfyoudonothaveanyideawhatIrsquomtalkingaboutProgrammersliketofeelsmartsotheyinventedobject-orientedprogrammingnameditOOPandthenuseditwaytoomuchIfyouthinkthatrsquoshardyoushouldtrytouseldquofunctionalprogrammingrdquo

6Find10examplesofthingsintherealworldthatwouldfitinalistTrywritingsomescriptstoworkwiththem

CommonStudentQuestionsDidnrsquotyousaytonotusewhile-loopsYessojustremembersometimesyoucanbreaktherulesifyouhaveagoodreasonOnlyidiotsareslavestorulesallthetime

Whydoesjoin(stuff)notworkThewaythedocumentationforjoiniswrittendoesnrsquotmakesenseItdoesnotworklikethatandisinsteadamethodyoucallontheinsertedstringtoputbetweenthelisttobejoinedRewriteitlikejoin(stuff)

Whydidyouuseawhile-loopTryrewritingitwithafor-loopandseeifthatrsquoseasier

Whatdoesstuff[35]doThatextractsaldquoslicerdquofromthestufflistthatisfromelement3toelement4meaningitdoesnotincludeelement5Itrsquossimilartohowrange(35)wouldwork

Exercise39DictionariesOhLovelyDictionaries

YouarenowgoingtolearnabouttheDictionarydatastructureinPythonADictionary(ordict)isawaytostoredatajustlikealistbutinsteadofusingonlynumberstogetthedatayoucanusealmostanythingThisletsyoutreatadictlikeitrsquosadatabaseforstoringandorganizingdataLetrsquoscomparewhatdictscandotowhatlistscandoYouseealistletsyoudothisClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtthings=[abcd]

gtgtgtprint(things[1])

b

gtgtgtthings[1]=z

gtgtgtprint(things[1])

z

gtgtgtthings

[azcd]

YoucanusenumberstoindexintoalistmeaningyoucanusenumberstofindoutwhatrsquosinlistsYoushouldknowthisaboutlistsbynowbutmakesureyouunderstandthatyoucanonlyusenumberstogetitemsoutofalistAdictletsyouuseanythingnotjustnumbersYesadictassociatesonethingtoanothernomatterwhatitisTakealookClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtstuff=nameZedage39height612+2

gtgtgtprint(stuff[name])

Zed

gtgtgtprint(stuff[age])

39

gtgtgtprint(stuff[height])

74

gtgtgtstuff[city]=SF

gtgtgtprint(stuff[city])

SF

YouwillseethatinsteadofjustnumberswersquoreusingstringstosaywhatwewantfromthestuffdictionaryWecanalsoputnewthingsintothedictionary

withstringsItdoesnrsquothavetobestringsthoughWecanalsodothisExercise39PythonSession

gtgtgtstuff[1]=Wow

gtgtgtstuff[2]=Neato

gtgtgtprint(stuff[1])

Wow

gtgtgtprint(stuff[2])

NeatoInthiscodeIusednumbersandthenyoucanseethereare

numbersandstringsaskeysinthedictwhenIprintitIcoulduse

anythingWellalmostbutjustpretendyoucanuseanythingfornow

OfcourseadictionarythatyoucanonlyputthingsinisprettystupidsoherersquoshowyoudeletethingswiththedelkeywordClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtdelstuff[city]

gtgtgtdelstuff[1]

gtgtgtdelstuff[2]

gtgtgtstuff

nameZedage39height74

ADictionaryExampleWersquollnowdoanexercisethatyoumuststudyverycarefullyIwantyoutotypethiscodeinandtrytounderstandwhatrsquosgoingonTakenoteofwhenyouputthingsinadictgetthemfromahashandalltheoperationsyouuseNoticehowthisexampleismappingstatestotheirabbreviationsandthentheabbreviationstocitiesinthestatesRemembermapping(orassociating)isthekeyconceptinadictionaryClickheretoviewcodeimage

ex39py

1createamappingofstatetoabbreviation

2states=

3OregonOR

4FloridaFL

5CaliforniaCA

6NewYorkNY

7MichiganMI

8

9

10createabasicsetofstatesandsomecitiesinthem

11cities=

12CASanFrancisco

13MIDetroit

14FLJacksonville

15

16

17addsomemorecities

18cities[NY]=NewYork

19cities[OR]=Portland

20

21printoutsomecities

22print(-10)

23print(NYStatehascities[NY])

24print(ORStatehascities[OR])

25

26printsomestates

27print(-10)

28print(Michigansabbreviationisstates[Michigan])

29print(Floridasabbreviationisstates[Florida])

30

31doitbyusingthestatethencitiesdict

32print(-10)

33print(Michiganhascities[states[Michigan]])

34print(Floridahascities[states[Florida]])

35

36printeverystateabbreviation

37print(-10)

38forstateabbrevinlist(statesitems())

39print(fstateisabbreviatedabbrev)

40

41printeverycityinstate

42print(-10)

43forabbrevcityinlist(citiesitems())

44print(fabbrevhasthecitycity)

45

46nowdobothatthesametime

47print(-10)

48forstateabbrevinlist(statesitems())

49print(fstatestateisabbreviatedabbrev)

50print(fandhascitycities[abbrev])

51

52print(-10)

53safelygetaabbreviationbystatethatmightnotbethere

54state=statesget(Texas)

55

56ifnotstate

57print(SorrynoTexas)

58

59getacitywithadefaultvalue

60city=citiesget(TXDoesNotExist)

61print(fThecityforthestateTXiscity)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise39Session

$python36ex39py

----------

NYStatehasNewYork

ORStatehasPortland

----------

MichigansabbreviationisMI

FloridasabbreviationisFL

----------

MichiganhasDetroit

FloridahasJacksonville

----------

OregonisabbreviatedOR

FloridaisabbreviatedFL

CaliforniaisabbreviatedCA

NewYorkisabbreviatedNY

MichiganisabbreviatedMI

----------

CAhasthecitySanFrancisco

MIhasthecityDetroit

FLhasthecityJacksonville

NYhasthecityNewYork

ORhasthecityPortland

----------

OregonstateisabbreviatedOR

andhascityPortland

FloridastateisabbreviatedFL

andhascityJacksonville

CaliforniastateisabbreviatedCA

andhascitySanFrancisco

NewYorkstateisabbreviatedNY

andhascityNewYork

MichiganstateisabbreviatedMI

andhascityDetroit

----------

SorrynoTexas

ThecityforthestateTXisDoesNotExist

WhatDictionariesCanDo

WhatDictionariesCanDoAdictionaryisanotherexampleofadatastructureandlikealistitisoneofthemostcommonlyuseddatastructuresinprogrammingAdictionaryisusedtomaporassociatethingsyouwanttostoretokeysyouneedtogetthemAgainprogrammersdonrsquotuseatermlikeldquodictionaryrdquoforsomethingthatdoesnrsquotworklikeanactualdictionaryfullofwordssoletrsquosusethatasourrealworldexampleLetrsquossayyouwanttofindoutwhatthewordldquohonorificabilitudinitatibusrdquomeansTodayyouwouldsimplycopy-pastethatwordintoasearchengineandthenfindouttheanswerandwecouldsayasearchengineislikeareallyhugesupercomplexversionoftheOxfordEnglishDictionary(OED)Beforesearchengineswhatyouwoulddoisthis1GotoyourlibraryandgetldquothedictionaryrdquoLetrsquossayitrsquostheOED

2YouknowldquohonorificabilitudinitatibusrdquostartswiththeletterldquoHrdquosoyoulookonthesideofthebookforthelittletabthathasldquoHrdquoonit

3Skimthepagesuntilyouareclosetowhereldquohonrdquostarts4SkimafewmorepagesuntilyoufindldquohonorificabilitudinitatibusrdquoorhitthebeginningoftheldquohprdquowordsandrealizethiswordisnrsquotintheOED

5Onceyoufindtheentryyoureadthedefinitiontofigureoutwhatitmeans

ThisprocessisnearlyexactlythewayadictworksandyouarebasicallyldquomappingrdquothewordldquohonorificabilitudinitatibusrdquotoitsdefinitionAdictinPythonisjustlikeadictionaryintherealworldsuchastheOED

StudyDrills1Dothissamekindofmappingwithcitiesandstatesregionsinyourcountryorsomeothercountry

2FindthePythondocumentationfordictionariesandtrytodoevenmorethingstothem

3FindoutwhatyoucanrsquotdowithdictionariesAbigoneisthattheydonothaveordersotryplayingwiththat

CommonStudentQuestionsWhatisthedifferencebetweenalistandadictionaryAlistisforanorderedlistofitemsAdictionary(ordict)isformatchingsomeitems(calledldquokeysrdquo)tootheritems(calledldquovaluesrdquo)

WhatwouldIuseadictionaryforWhenyouhavetotakeonevalueandldquolookuprdquoanothervalueInfactyoucouldcalldictionariesldquolookuptablesrdquo

WhatwouldIusealistforUsealistforanysequenceofthingsthatneedstobeinorderandyouonlyneedtolookthemupbyanumericindex

WhatifIneedadictionarybutIneedittobeinorderTakealookatthecollectionsOrderedDictdatastructureinPythonSearchforitonlinetofindthedocumentation

Exercise40ModulesClassesandObjects

Pythoniscalledanldquoobject-orientedprogramminglanguagerdquoThismeansthereisaconstructinPythoncalledaclassthatletsyoustructureyoursoftwareinaparticularwayUsingclassesyoucanaddconsistencytoyourprogramssothattheycanbeusedinacleanerwayAtleastthatrsquosthetheoryIamnowgoingtoteachyouthebeginningsofobject-orientedprogrammingclassesandobjectsusingwhatyoualreadyknowaboutdictionariesandmodulesMyproblemisthatobject-orientedprogramming(OOP)isjustplainweirdYouhavetostrugglewiththistrytounderstandwhatIsayheretypeinthecodeandinthenextexerciseIrsquollhammeritinHerewego

ModulesAreLikeDictionariesYouknowhowadictionaryiscreatedandusedandthatitisawaytomaponethingtoanotherThatmeansifyouhaveadictionarywithakeyldquoapplerdquoandyouwanttogetitthenyoudothisClickheretoviewcodeimage

ex40apy

1mystuff=appleIAMAPPLES

2print(mystuff[apple])

KeepthisideaofldquogetXfromYrdquoinyourheadandnowthinkaboutmodulesYoursquovemadeafewsofarandyoushouldknowtheyare1APythonfilewithsomefunctionsorvariablesinit

2Whichyoucanimport3Andaccessthefunctionsorvariablesofwiththe(dot)operator

ImagineIhaveamodulethatIdecidetonamemystuffpyandIputafunctioninitcalledappleHerersquosthemodulemystuffpyClickheretoviewcodeimage

ex40apy

1thisgoesinmystuffpy

2defapple()

3print(IAMAPPLES)OnceIhavethiscodeIcanusethe

moduleMyStuffwithimportandthenaccesstheapplefunction

ex40apy

1importmystuff

2mystuffapple()Icouldalsoputavariableinitnamed

tangerineClickheretoviewcodeimage

ex40apy

1defapple()

2print(IAMAPPLES)

3

4thisisjustavariable

5tangerine=Livingreflectionofadream

Icanaccessthatthesamewayex40apy

1importmystuff

2

3mystuffapple()

4print(mystufftangerine)Referbacktothedictionaryandyou

shouldstarttoseehowthisissimilartousingadictionarybut

thesyntaxisdifferentLetrsquoscompareClickheretoviewcodeimage

ex40apy

1mystuff[apple]getapplefromdict

2mystuffapple()getapplefromthemodule

3mystufftangerinesamethingitsjustavariableThismeans

wehaveaverycommonpatterninPython1Takeakey=valuestyle

container

2GetsomethingoutofitbythekeyrsquosnameInthecaseofthedictionarythekeyisastringandthesyntaxis[key]InthecaseofthemodulethekeyisanidentifierandthesyntaxiskeyOtherthanthattheyarenearlythesamething

ClassesAreLikeModulesYoucanthinkaboutamoduleasaspecializeddictionarythatcanstorePythoncodesoyoucanaccessitwiththeoperatorPythonalsohasanotherconstructthatservesasimilarpurposecalledaclassAclassisawaytotakeagroupingof

functionsanddataandplacetheminsideacontainersoyoucanaccessthemwiththe(dot)operatorIfIweretocreateaclassjustlikethemystuffmoduleIrsquoddosomethinglikethisClickheretoviewcodeimage

ex40apy

1classMyStuff(object)

2

3def__init__(self)

4selftangerine=Andnowathousandyearsbetween

5

6defapple(self)

7print(IAMCLASSYAPPLES)Thatlookscomplicated

comparedtomodulesandthereisdefinitelyalotgoingonby

comparisonbutyoushouldbeabletomakeouthowthisislikea

ldquomini-modulerdquowithMyStuffhavinganapple()functioninitWhatis

probablyconfusingisthe__init__()functionanduseof

selftangerineforsettingthetangerineinstancevariable

HerersquoswhyclassesareusedinsteadofmodulesYoucantakethisMyStuffclassanduseittocraftmanyofthemmillionsatatimeifyouwantandeachonewonrsquotinterferewitheachotherWhenyouimportamodulethereisonlyonefortheentireprogramunlessyoudosomemonsterhacksBeforeyoucanunderstandthisthoughyouneedtoknowwhatanldquoobjectrdquoisandhowtoworkwithMyStuffjustlikeyoudowiththemystuffpymodule

ObjectsAreLikeImportIfaclassislikealdquomini-modulerdquothentherehastobeaconceptsimilartoimportbutforclassesThatconceptiscalledldquoinstantiaterdquowhichisjustafancyobnoxiousoverlysmartwaytosayldquocreaterdquoWhenyouinstantiateaclasswhatyougetiscalledanobjectYouinstantiate(create)aclassbycallingtheclasslikeitrsquosafunctionlikethisex40apy

1thing=MyStuff()

2thingapple()

3print(thingtangerine)Thefirstlineistheldquoinstantiaterdquo

operationanditrsquosalotlikecallingafunctionHoweverPython

coordinatesasequenceofeventsforyoubehindthescenesIrsquollgo

throughthesestepsusingtheprecedingcodeforMyStuff1Python

looksforMyStuff()andseesthatitisaclassyoursquovedefined

2Pythoncraftsanemptyobjectwithallthefunctionsyoursquovespecifiedintheclassusingdef

3Pythonthenlookstoseeifyoumadealdquomagicrdquo__init__functionandifyouhaveitcallsthatfunctiontoinitializeyournewlycreatedemptyobject

4IntheMyStufffunction__init__youthengetthisextravariableselfwhichisthatemptyobjectPythonmadeforyouandyoucansetvariablesonitjustlikeyouwouldwithamoduledictionaryorotherobject

5Inthiscaseyousetselftangerinetoasonglyricandthenyoursquoveinitializedthisobject

6NowPythoncantakethisnewlymintedobjectandassignittothethingvariableforyoutoworkwith

ThatrsquosthebasicsofhowPythondoesthisldquomini-importrdquowhenyoucallaclasslikeafunctionRememberthatthisisnotgivingyoutheclassbutinsteadisusingtheclassasablueprintforbuildingacopyofthattypeofthingKeepinmindthatIrsquomgivingyouaslightlyinaccurateideaofhowtheseworksothatyoucanstarttobuildupanunderstandingofclassesbasedonwhatyouknowaboutmodulesThetruthisclassesandobjectssuddenlydivergefrommodulesatthispointIfIwerebeingtotallyhonestIrsquodsaysomethingmorelikethisbullClassesarelikeblueprintsordefinitionsforcreatingnewmini-modules

bullInstantiationishowyoumakeoneofthesemini-modulesandimportitatthesametimeldquoInstantiaterdquojustmeanstocreateanobjectfromtheclass

bullTheresultingcreatedmini-moduleiscalledanobjectandyouthenassignittoavariabletoworkwithit

Atthispointobjectsbehavedifferentlyfrommodulesandthisshouldonlyserveasawayforyoutobridgeovertounderstandingclassesandobjects

GettingThingsfromThingsInowhavethreewaystogetthingsfromthingsClickheretoviewcodeimage

ex40apy

1dictstyle

2mystuff[apples]

3

4modulestyle

5mystuffapples()

6print(mystufftangerine)

7

8classstyle

9thing=MyStuff()

10thingapples()

11print(thingtangerine)

AFirstClassExampleYoushouldstartseeingthesimilaritiesinthesethreekey=valuecontainertypesandprobablyhaveabunchofquestionsHangonwiththequestionsasthenextexercisewillhammerhomeyourldquoobject-orientedvocabularyrdquoInthisexerciseIjustwantyoutotypeinthiscodeandgetitworkingsothatyouhavesomeexperiencebeforemovingonClickheretoviewcodeimage

ex40py

1classSong(object)

2

3def__init__(selflyrics)

4selflyrics=lyrics

5

6defsing_me_a_song(self)

7forlineinselflyrics

8print(line)

9

10happy_bday=Song([Happybirthdaytoyou

11Idontwanttogetsued

12SoIllstoprightthere])

13

14bulls_on_parade=Song([Theyrallyaroundthafamily

15Withpocketsfullofshells])

16

17happy_bdaysing_me_a_song()

18

19bulls_on_paradesing_me_a_song()

WhatYouShouldSee

Exercise40Session

$python36ex40py

Happybirthdaytoyou

Idontwanttogetsued

SoIllstoprightthere

Theyrallyaroundthafamily

Withpocketsfullofshells

StudyDrills1Writesomemoresongsusingthisandmakesureyouunderstandthatyoursquorepassingalistofstringsasthelyrics

2Putthelyricsinaseparatevariablethenpassthatvariabletotheclasstouseinstead

3SeeifyoucanhackonthisandmakeitdomorethingsDonrsquotworryifyouhavenoideahowjustgiveitatryandseewhathappensBreakittrashitthrashityoucanrsquothurtit

4Searchonlineforldquoobject-orientedprogrammingrdquoandtrytooverflowyourbrainwithwhatyoureadDonrsquotworryifitmakesabsolutelynosensetoyouHalfofthatstuffmakesnosensetometoo

CommonStudentQuestionsWhydoIneedselfwhenImake__init__orotherfunctionsforclassesIfyoudonrsquothaveselfthencodelikecheese=FrankisambiguousThatcodeisnrsquotclearaboutwhetheryoumeantheinstancersquoscheeseattributeoralocalvariablenamedcheeseWithselfcheese=Frankitrsquosveryclearyoumeantheinstanceattributeselfcheese

Exercise41LearningtoSpeakObject-Oriented

InthisexerciseIrsquomgoingtoteachyouhowtospeakldquoobject-orientedrdquoWhatIrsquolldoisgiveyouasmallsetofwordswithdefinitionsyouneedtoknowThenIrsquollgiveyouasetofsentenceswithholesinthemthatyoursquollhavetounderstandFinallyIrsquomgoingtogiveyoualargesetofexercisesthatyouhavetocompletetomakethesesentencessolidinyourvocabulary

WordDrillsclassTellPythontomakeanewtypeofthingobjectTwomeaningsthemostbasictypeofthingandanyinstanceofsomething

instanceWhatyougetwhenyoutellPythontocreateaclassdefHowyoudefineafunctioninsideaclassselfInsidethefunctionsinaclassselfisavariablefortheinstanceobjectbeingaccessed

inheritanceTheconceptthatoneclasscaninherittraitsfromanotherclassmuchlikeyouandyourparents

compositionTheconceptthataclasscanbecomposedofotherclassesaspartsmuchlikehowacarhaswheels

attributeApropertyclasseshavethatarefromcompositionandareusuallyvariables

is-aAphrasetosaythatsomethinginheritsfromanotherasinaldquosalmonrdquois-ardquofishldquo

has-aAphrasetosaythatsomethingiscomposedofotherthingsorhasatraitasinldquoasalmonhas-amouthrdquo

TakesometimetomakeflashcardsforthesetermsandmemorizethemAsusualthiswonrsquotmaketoomuchsenseuntilafteryouarefinishedwiththisexercisebutyouneedtoknowthebasewordsfirst

PhraseDrillsNextIhavealistofPythoncodesnippetsontheleftandtheEnglishsentencesforthem

classX(Y)ldquoMakeaclassnamedXthatis-aYrdquo

classX(object)def__init__(selfJ)ldquoclassXhas-a__init__thattakesselfandJparametersrdquo

classX(object)defM(selfJ)ldquoclassXhas-afunctionnamedMthattakesselfandJparametersrdquo

foo=X()ldquoSetfootoaninstanceofclassXrdquofooM(J)ldquoFromfoogettheMfunctionandcallitwithparametersselfJrdquo

fooK=QldquoFromfoogettheKattributeandsetittoQrdquoIneachofthesewhereyouseeXYMJKQandfooyoucantreatthoselikeblankspotsForexampleIcanalsowritethesesentencesasfollows1ldquoMakeaclassnamedthatis-aYrdquo

2ldquoclasshas-a__init__thattakesselfandparametersrdquo3ldquoclasshas-afunctionnamedthattakesselfandparametersrdquo4ldquoSettoaninstanceofclassrdquo5ldquoFromgetthefunctionandcallitwithself=andparametersrdquo

6ldquoFromgettheattributeandsetittordquoAgainwritetheseonsomeflashcardsanddrillthemPutthePythoncodesnippetonthefrontandthesentenceonthebackYouhavetobeabletosaythesentenceexactlythesameeverytimewheneveryouseethatformNotsortofthesamebutexactlythesame

CombinedDrillsThefinalpreparationforyouistocombinethewordsdrillswiththephrasedrillsWhatIwantyoutodoforthisdrillisthis

1Takeaphrasecardanddrillit2Flipitoverandreadthesentenceandforeachwordinthesentencethatisinyourwordsdrillsgetthatcard

3Drillthosewordsforthatsentence4Keepgoinguntilyouareboredthentakeabreakanddoitagain

AReadingTestInowhavealittlePythonhackscriptthatwilldrillyouonthesewordsyouknowinaninfinitemannerThisisasimplescriptyoushouldbeabletofigureoutandtheonlythingitdoesisusealibrarycalledurllibtodownloadalist

ofwordsIhaveHerersquosthescriptwhichyoushouldenterintooop_testpytoworkwithitClickheretoviewcodeimage

ex41py

1importrandom

2fromurllibrequestimporturlopen

3importsys

4

5WORD_URL=httplearncodethehardwayorgwordstxt

6WORDS=[]

7

8PHRASES=

9class()

10Makeaclassnamedthatis-a

11class(object)ntdef__init__(self)

12classhas-a__init__thattakesselfand

params

13class(object)ntdef(self)

14classhas-afunctionthattakesselfand

params

15=()

16Settoaninstanceofclass

17()

18Fromgetthefunctioncallitwithparamsself

19=

20Fromgettheattributeandsetitto

21

22

23dotheywanttodrillphrasesfirst

24iflen(sysargv)==2andsysargv[1]==english

25PHRASE_FIRST=True

26else

27PHRASE_FIRST=False

28

29loadupthewordsfromthewebsite

30forwordinurlopen(WORD_URL)readlines()

31WORDSappend(str(wordstrip()encoding=utf-8))

32

33

34defconvert(snippetphrase)

35class_names=[wcapitalize()forwin

36randomsample(WORDSsnippetcount())]

37other_names=randomsample(WORDSsnippetcount())

38results=[]

39param_names=[]

40

41foriinrange(0snippetcount())

42param_count=randomrandint(13)

43param_namesappend(join(

44randomsample(WORDSparam_count)))

45

46forsentenceinsnippetphrase

47result=sentence[]

48

49fakeclassnames

50forwordinclass_names

51result=resultreplace(word1)

52

53fakeothernames

54forwordinother_names

55result=resultreplace(word1)

56

57fakeparameterlists

58forwordinparam_names

59result=resultreplace(word1)

60

61resultsappend(result)

62

63returnresults

64

65

66keepgoinguntiltheyhitCTRL-D

67try

68whileTrue

69snippets=list(PHRASESkeys())

70randomshuffle(snippets)

71

72forsnippetinsnippets

73phrase=PHRASES[snippet]

74questionanswer=convert(snippetphrase)

75ifPHRASE_FIRST

76questionanswer=answerquestion

77

78print(question)

79

80input(lt)

81print(fANSWERanswernn)

82exceptEOFError

83print(nBye)Runthisscriptandtrytotranslatethe

ldquoobject-orientedphrasesrdquointoEnglishtranslationsYoushouldsee

thatthePHRASESdicthasbothformsandthatyoujusthavetoenter

thecorrectone

PracticeEnglishtoCode

PracticeEnglishtoCodeNextyoushouldrunthescriptwiththeldquoenglishrdquooptionsothatyoudrilltheinverseoperation

$pythonoop_testpyenglishRememberthatthesephrasesareusing

nonsensewordsPartoflearningtoreadcodewellistostopplacing

somuchmeaningonthenamesusedforvariablesandclassesToo

oftenpeoplewillreadawordlikeldquoCorkrdquoandsuddenlygetderailed

becausethatwordwillconfusethemaboutthemeaningIntheabove

exampleldquoCorkrdquoisjustanarbitrarynamechosenforaclassDonrsquot

placeanyothermeaningonitandinsteadtreatitlikethepatterns

Irsquovegivenyou

ReadingMoreCodeYouarenowtogoonanewquesttoreadevenmorecodetoreadthephrasesyoujustlearnedinthecodeyoureadYouwilllookforallthefileswithclassesandthendothefollowing

1Foreachclassgiveitsnameandwhatotherclassesitinheritsfrom2Underthatlisteveryfunctionithasandtheparameterstheytake3Listalloftheattributesitusesonitsself4Foreachattributegivetheclassthisattributeis

ThegoalistogothroughrealcodeandstartlearningtoldquopatternmatchrdquothephrasesyoujustlearnedagainsthowtheyrsquoreusedIfyoudrillthisenoughyoushouldstarttoseethesepatternsshoutatyouinthecodewhereasbeforetheyjustseemedlikevagueblankspotsyoudidnrsquotknow

CommonStudentQuestionsWhatdoesresult=sentence[]doThatrsquosaPythonwayofcopyingalistYoursquoreusingthelistslicesyntax[]toeffectivelymakeaslicefromtheveryfirstelementtotheverylastone

ThisscriptishardtogetrunningBythispointyoushouldbeabletotypethisinandgetitworkingItdoeshaveafewlittletrickshereandtherebuttherersquosnothingcomplexaboutitJustdoallthethingsyoursquovelearnedsofartodebugscriptsTypeeachlineinconfirmthatitrsquosexactlylikemineandresearchanythingyoudonrsquotknowonline

ItrsquosstilltoohardYoucandothisTakeitveryslowcharacterbycharacterifyouhavetobuttypeitinexactlyandfigureoutwhatitdoes

Exercise42Is-AHas-AObjectsandClasses

AnimportantconceptthatyouhavetounderstandisthedifferencebetweenaclassandanobjectTheproblemisthereisnorealldquodifferencerdquobetweenaclassandanobjectTheyareactuallythesamethingatdifferentpointsintimeIwilldemonstratewithaZenkoanWhatisthedifferencebetweenafishandasalmonDidthatquestionsortofconfuseyouReallysitdownandthinkaboutitforaminuteImeanafishandasalmonaredifferentbutwaittheyarethesamethingrightAsalmonisakindoffishsoImeanitrsquosnotdifferentButatthesametimeasalmonisaparticulartypeoffishsoitrsquosactuallydifferentfromallotherfishThatrsquoswhatmakesitasalmonandnotahalibutSoasalmonandafisharethesamebutdifferentWeirdThisquestionisconfusingbecausemostpeopledonotthinkaboutrealthingsthiswaybuttheyintuitivelyunderstandthemYoudonotneedtothinkaboutthedifferencebetweenafishandasalmonbecauseyouknowhowtheyarerelatedYouknowasalmonisakindoffishandthatthereareotherkindsoffishwithouthavingtounderstandthatLetrsquostakeitonestepfurtherLetrsquossayyouhaveabucketfullofthreesalmonandbecauseyouareanicepersonyouhavedecidedtonamethemFrankJoeandMaryNowthinkaboutthisquestionWhatisthedifferencebetweenMaryandasalmonAgainthisisaweirdquestionbutitrsquosabiteasierthanthefishversussalmonquestionYouknowthatMaryisasalmonsoshersquosnotreallydifferentShersquosjustaspecificldquoinstancerdquoofasalmonJoeandFrankarealsoinstancesofsalmonWhatdoImeanwhenIsayinstanceImeantheywerecreatedfromsomeothersalmonandnowrepresentarealthingthathassalmon-likeattributesNowforthemind-bendingideaFishisaclassandSalmonisaclassandMaryisanobjectThinkaboutthatforasecondLetrsquosbreakitdownslowlyandseeifyougetitAfishisaclassmeaningitrsquosnotarealthingbutratherawordweattachtoinstancesofthingswithsimilarattributesGotfinsGotgillsLivesinwaterAlrightitrsquosprobablyafishSomeonewithaPhDthencomesalongandsaysldquoNomyyoungfriendthisfishisactuallySalmosalaraffectionatelyknownasasalmonrdquoThisprofessorhasjustclarifiedthefishfurtherandmadeanewclasscalledldquoSalmonrdquothathas

morespecificattributesLongernosereddishfleshbiglivesintheoceanorfreshwatertastyProbablyasalmonFinallyacookcomesalongandtellsthePhDldquoNoyouseethisSalmonrighthereIrsquollcallherMaryandIrsquomgoingtomakeatastyfilletoutofherwithanicesaucerdquoNowyouhavethisinstanceofasalmon(whichalsoisaninstanceofafish)namedMaryturnedintosomethingrealthatisfillingyourbellyIthasbecomeanobjectThereyouhaveitMaryisakindofsalmonthatisakindoffishmdashobjectisaclassisaclass

HowThisLooksinCodeThisisaweirdconceptbuttobeveryhonestyouonlyhavetoworryaboutitwhenyoumakenewclassesandwhenyouuseaclassIwillshowyoutwotrickstohelpyoufigureoutwhethersomethingisaclassoranobjectFirstyouneedtolearntwocatchphrasesldquois-ardquoandldquohas-ardquoYouusethephraseis-awhenyoutalkaboutobjectsandclassesbeingrelatedtoeachotherbyaclassrelationshipYouusehas-awhenyoutalkaboutobjectsandclassesthatarerelatedonlybecausetheyreferenceeachotherNowgothroughthispieceofcodeandreplaceeachcommentwithacommentthatsayswhetherthenextlinerepresentsanis-aorahas-arelationshipandwhatthatrelationshipisInthebeginningofthecodeIrsquovelaidoutafewexamplessoyoujusthavetowritetheremainingonesRememberis-aistherelationshipbetweenfishandsalmonwhilehas-aistherelationshipbetweensalmonandgillsClickheretoviewcodeimage

ex42py

1Animalis-aobject(yessortofconfusing)lookatthe

extracredit

2classAnimal(object)

3pass

4

5

6classDog(Animal)

7

8def__init__(selfname)

9

10selfname=name

11

12

13classCat(Animal)

14

15def__init__(selfname)

16

17selfname=name

18

19

20classPerson(object)

21

22def__init__(selfname)

23

24selfname=name

25

26Personhas-apetofsomekind

27selfpet=None

28

29

30classEmployee(Person)

31

32def__init__(selfnamesalary)

33hmmwhatisthisstrangemagic

34super(Employeeself)__init__(name)

35

36selfsalary=salary

37

38

39classFish(object)

40pass

41

42

43classSalmon(Fish)

44pass

45

46

47classHalibut(Fish)

48pass

49

50

51roveris-aDog

52rover=Dog(Rover)

53

54

55satan=Cat(Satan)

56

57

58mary=Person(Mary)

59

60

61marypet=satan

62

63

64frank=Employee(Frank120000)

65

66

67frankpet=rover

68

69

70flipper=Fish()

71

72

73crouse=Salmon()

74

75

76harry=Halibut()

AboutclassName(object)InPython3youdonotneedtoaddthe(object)afterthenameoftheclassbutthePythoncommunitybelievesinldquoexplicitisbetterthanimplicitrdquosoIandotherPythonexpertshavedecidedtoincludeitYoumayrunintocodethatdoesnothave(object)aftersimpleclassesandthoseclassesareperfectlyfineandwillworkwithclassesyoucreatethatdohave(object)AtthispointitissimplyextradocumentationandhasnoimpactonhowyourclassesworkInPython2therewasadifferencebetweenthetwotypesofclassesbutnowyoudonrsquothavetoworryaboutitTheonlytrickyparttousing(object)involvesthementalgymnasticsofsayingldquoclassNameisaclassoftypeobjectrdquoThatmaysoundconfusingtoyounowsinceitrsquosaclassthatrsquosanameobjectthatrsquosaclassbutdonrsquotfeelbadaboutthatJustthinkofclassName(object)assayingldquothisisabasicsimpleclassrdquoandyoursquollbefineFinallyinthefuturethestylesandtastesofPythonprogrammersmaychangeandthisexplicituseof(object)mightbeseenasasignthatyouareabadprogrammerIfthathappenssimplystopusingitortellthemldquoPythonZensaysexplicitisbetterthanimplicitrdquo

StudyDrills1ResearchwhyPythonaddedthisstrangeobjectclassandwhatthatmeans2Isitpossibletouseaclasslikeitrsquosanobject3FillouttheanimalsfishandpeopleinthisexercisewithfunctionsthatmakethemdothingsSeewhathappenswhenfunctionsareinaldquobase

classrdquolikeAnimalversusinsayDog4Findotherpeoplersquoscodeandworkoutalltheis-aandhas-arelationships5Makesomenewrelationshipsthatarelistsanddictionariessoyoucanalsohaveldquohas-manyrdquorelationships

6Doyouthinktherersquossuchthingasanldquois-manyrdquorelationshipReadaboutldquomultipleinheritancerdquothenavoiditifyoucan

CommonStudentQuestionsWhatarethesecommentsforThoseareldquofill-in-the-blankrdquocommentsthatyouaresupposedtofillinwiththerightis-aandhas-aconceptsReadthisexerciseagainandlookattheothercommentstoseewhatImean

Whatisthepointofselfpet=NoneThatmakessurethattheselfpetattributeofthatclassissettoadefaultofNone

Whatdoessuper(Employeeself)__init__(name)doThatrsquoshowyoucanrunthe__init__methodofaparentclassreliablySearchforldquopython36superrdquoandreadthevariousadviceonitbeingevilandgoodforyou

Exercise43BasicObject-OrientedAnalysisandDesign

IrsquomgoingtodescribeaprocesstousewhenyouwanttobuildsomethingusingPythonspecificallywithobject-orientedprogramming(OOP)WhatImeanbyaldquoprocessrdquoisthatIrsquollgiveyouasetofstepsthatyoudoinorderbutthatyouarenrsquotmeanttobeaslavetoandthatmightnotalwaysworkforeveryproblemTheyarejustagoodstartingpointformanyprogrammingproblemsandshouldnrsquotbeconsideredtheonlywaytosolvethesetypesofproblemsThisprocessisjustonewaytodoitthatyoucanfollowTheprocessisasfollows1Writeordrawabouttheproblem

2Extractkeyconceptsfrom1andresearchthem3Createaclasshierarchyandobjectmapfortheconcepts4Codetheclassesandatesttorunthem5Repeatandrefine

ThewaytolookatthisprocessisthatitisldquotopdownrdquomeaningitstartsfromtheveryabstractlooseideaandthenslowlyrefinesituntiltheideaissolidandsomethingyoucancodeIstartbyjustwritingabouttheproblemandtryingtothinkupanythingIcanaboutitMaybeIrsquollevendrawadiagramortwomaybeamapofsomekindorevenwritemyselfaseriesofemailsdescribingtheproblemThisgivesmeawaytoexpressthekeyconceptsintheproblemandalsoexplorewhatImightalreadyknowaboutitThenIgothroughthesenotesdrawingsanddescriptionsandIpulloutthekeyconceptsTherersquosasimpletricktodoingthisImakealistofallthenounsandverbsinmywritinganddrawingsthenwriteouthowtheyrsquorerelatedThisgivesmeagoodlistofnamesforclassesobjectsandfunctionsinthenextstepItakethislistofconceptsandthenresearchanythatIdonrsquotunderstandsoIcanrefinethemfurtherifneededOnceIhavemylistofconceptsIcreateasimpleoutlinetreeoftheconceptsandhowtheyarerelatedasclassesIcanusuallytakemylistofnounsandstartaskingldquoIsthisonelikeotherconceptnounsThatmeanstheyhaveacommonparentclasssowhatisitcalledrdquoIkeepdoingthisuntilIhaveaclasshierarchythatrsquosjustasimpletreelistoradiagramThenItaketheverbsIhaveandseeifthosearefunctionnamesforeachclassandputtheminmytree

WiththisclasshierarchyfiguredoutIsitdownandwritesomebasicskeletoncodethathasjusttheclassestheirfunctionsandnothingmoreIthenwriteatestthatrunsthiscodeandmakessuretheclassesIrsquovemademakesenseandworkrightSometimesImaywritethetestfirstandothertimesImightwritealittletestalittlecodealittletestandsoonuntilIhavethewholethingbuiltFinallyIkeepcyclingoverthisprocessrepeatingitandrefiningasIgoandmakingitasclearasIcanbeforedoingmoreimplementationIfIgetstuckatanyparticularpartbecauseofaconceptorproblemIhavenrsquotanticipatedthenIsitdownandstarttheprocessoveronjustthatparttofigureitoutmorebeforecontinuingIwillnowgothroughthisprocesswhilecomingupwithagameengineandagameforthisexercise

TheAnalysisofaSimpleGameEngineThegameIwanttomakeiscalledldquoGothonsfromPlanetPercal25rdquoanditwillbeasmallspaceadventuregameWithnothingmorethanthatconceptinmymindIcanexploretheideaandfigureouthowtomakethegamecometolife

WriteorDrawAbouttheProblemIrsquomgoingtowritealittleparagraphforthegameldquoAlienshaveinvadedaspaceshipandourherohastogothroughamazeofroomsdefeatingthemsohecanescapeintoanescapepodtotheplanetbelowThegamewillbemorelikeaZorkorAdventuretypegamewithtextoutputsandfunnywaystodieThegamewillinvolveanenginethatrunsamapfullofroomsorscenesEachroomwillprintitsowndescriptionwhentheplayerentersitandthentelltheenginewhatroomtorunnextoutofthemaprdquoAtthispointIhaveagoodideaforthegameandhowitwouldrunsonowIwanttodescribeeachsceneDeathThisiswhentheplayerdiesandshouldbesomethingfunny

CentralCorridorThisisthestartingpointandhasaGothonalreadystandingtherethattheplayershavetodefeatwithajokebeforecontinuing

LaserWeaponArmoryThisiswheretheherogetsaneutronbombtoblowuptheshipbeforegettingtotheescapepodIthasakeypadtheherohastoguessthenumberfor

TheBridgeThisisanotherbattlescenewithaGothonwheretheheroplacesthebomb

EscapePodThisiswheretheheroescapesbutonlyafterguessingtherightescapepod

AtthispointImightdrawoutamapofthesemaybewritemoredescriptionsofeachroommdashwhatevercomestomindasIexploretheproblem

ExtractKeyConceptsandResearchThemInowhaveenoughinformationtoextractsomeofthenounsandanalyzetheirclasshierarchyFirstImakealistofallthenouns

bullAlienbullPlayerbullShipbullMazebullRoombullScenebullGothonbullEscapePodbullPlanetbullMapbullEnginebullDeathbullCentralCorridorbullLaserWeaponArmorybullTheBridge

IwouldalsopossiblygothroughalltheverbsandseeifanyofthemmightbegoodfunctionnamesbutIrsquollskipthatfornowAtthispointImightalsoresearcheachoftheseconceptsandanythingIdonrsquotknowrightnowForexampleImightplayafewofthesetypesofgamesandmakesureIknowhowtheyworkImightresearchhowshipsaredesignedorhowbombsworkMaybeIrsquollresearchsometechnicalissuelikehowtostorethegamersquosstateinadatabaseAfterIrsquovedonethisresearchImightstartoveratstep1basedonnewinformationIhaveandrewritemydescriptionandextractnewconcepts

CreateaClassHierarchyandObjectMapfortheConceptsOnceIhavethatIturnitintoaclasshierarchybyaskingldquoWhatissimilartootherthingsrdquoIalsoaskldquoWhatisbasicallyjustanotherwordforanotherthingrdquo

RightawayIseethatldquoRoomrdquoandldquoScenerdquoarebasicallythesamethingdependingonhowIwanttodothingsIrsquomgoingtopickldquoScenerdquoforthisgameThenIseethatallthespecificroomslikeldquoCentralCorridorrdquoarebasicallyjustScenesIseealsothatDeathisbasicallyaScenewhichconfirmsmychoiceofldquoScenerdquooverldquoRoomrdquosinceyoucanhaveadeathscenebutadeathroomiskindofoddldquoMazerdquoandldquoMaprdquoarebasicallythesamesoIrsquomgoingtogowithldquoMaprdquosinceIuseditmoreoftenIdonrsquotwanttodoabattlesystemsoIrsquomgoingtoignoreldquoAlienrdquoandldquoPlayerrdquoandsavethatforlaterTheldquoPlanetrdquocouldalsojustbeanothersceneinsteadofsomethingspecificAfterallofthatthoughtprocessIstarttomakeaclasshierarchythatlookslikethisinmytexteditorMapEngineSceneDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodIthengothroughandfigureoutwhatactionsareneededoneachthingbasedonverbsinthedescriptionForexampleIknowfromthedescriptionIrsquomgoingtoneedawaytoldquorunrdquotheengineldquogetthenextscenerdquofromthemapgettheldquoopeningscenerdquoandldquoenterrdquoasceneIrsquolladdthoselikethisMapndashnext_scenendashopening_sceneEnginendashplayScenendashenterDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodNoticehowIjustput-enterunderScenesinceIknowthatallthescenesunderitwillinherititandhavetooverrideitlater

CodetheClassesandaTesttoRunThemOnceIhavethistreeofclassesandsomeofthefunctionsIopenupasourcefileinmyeditorandtrytowritethecodeforitUsuallyIrsquolljustcopy-pastethetreeintothesourcefileandthenedititintoclassesHerersquosasmallexampleofhow

intothesourcefileandthenedititintoclassesHerersquosasmallexampleofhowthismightlookatfirstwithasimplelittletestattheendofthefileClickheretoviewcodeimage

ex43_classespy

1classScene(object)

2

3defenter(self)

4pass

5

6

7classEngine(object)

8

9def__init__(selfscene_map)

10pass

11

12defplay(self)

13pass

14

15classDeath(Scene)

16

17defenter(self)

18pass

19

20classCentralCorridor(Scene)

21

22defenter(self)

23pass

24

25classLaserWeaponArmory(Scene)

26

27defenter(self)

28pass

29

30classTheBridge(Scene)

31

32defenter(self)

33pass

34

35classEscapePod(Scene)

36

37defenter(self)

38pass

39

40

41classMap(object)

42

43def__init__(selfstart_scene)

44pass

45

46defnext_scene(selfscene_name)

47pass

48

49defopening_scene(self)

50pass

51

52

53a_map=Map(central_corridor)

54a_game=Engine(a_map)

55a_gameplay()InthisfileyoucanseethatIsimplyreplicated

thehierarchyIwantedandthenaddedalittlebitofcodeattheend

torunitandseeifitallworksinthisbasicstructureInthe

latersectionsofthisexerciseyoursquollfillintherestofthiscode

andmakeitworktomatchthedescriptionofthegame

RepeatandRefineThelaststepinmylittleprocessisnrsquotsomuchastepasitisawhile-loopYoudonrsquoteverdothisasaone-passoperationInsteadyougobackoverthewholeprocessagainandrefineitbasedoninformationyoursquovelearnedfromlaterstepsSometimesIrsquollgettostep3andrealizethatIneedtoworkon1and2moresoIrsquollstopandgobackandworkonthoseSometimesIrsquollgetaflashofinspirationandjumptotheendtocodeupthesolutioninmyheadwhileIhaveittherebutthenIrsquollgobackanddothepreviousstepstomakesureIcoverallthepossibilitiesIhaveTheotherideainthisprocessisthatitrsquosnotjustsomethingyoudoatonesinglelevelbutsomethingthatyoucandoateverylevelwhenyourunintoaparticularproblemLetrsquossayIdonrsquotknowhowtowritetheEngineplaymethodyetIcanstopanddothiswholeprocessonjustthatonefunctiontofigureouthowtowriteit

TopDownversusBottomUpTheprocessistypicallylabeledldquotopdownrdquosinceitstartsatthemostabstractconcepts(thetop)andworksitswaydowntoactualimplementationIwantyoutousethisprocessIjustdescribedwhenanalyzingproblemsinthebookfromnowonbutyoushouldknowthattherersquosanotherwaytosolveproblemsinprogrammingthatstartswithcodeandgoesldquouprdquototheabstractconceptsThisotherwayislabeledldquobottomuprdquoHerearethegeneralstepsyoufollowtodothis

1Takeasmallpieceoftheproblemhackonsomecodeandgetittorunbarely

barely2Refinethecodeintosomethingmoreformalwithclassesandautomatedtests

3Extractthekeyconceptsyoursquoreusingandresearchthem4Writeadescriptionofwhatrsquosreallygoingon5Gobackandrefinethecodepossiblythrowingitoutandstartingover6Repeatmovingontosomeotherpieceoftheproblem

IfindthisprocessisbetteronceyoursquoremoresolidatprogrammingandarenaturallythinkingincodeaboutproblemsThisprocessisverygoodwhenyouknowsmallpiecesoftheoverallpuzzlebutmaybedonrsquothaveenoughinformationyetabouttheoverallconceptBreakingitdowninlittlepiecesandexploringwithcodethenhelpsyouslowlygrindawayattheproblemuntilyoursquovesolveditHoweverrememberthatyoursolutionwillprobablybemeanderingandweirdsothatrsquoswhymyversionofthisprocessinvolvesgoingbackandfindingresearchthencleaningthingsupbasedonwhatyoursquovelearned

TheCodeforldquoGothonsfromPlanetPercal25rdquoStopIrsquomgoingtoshowyoumyfinalsolutiontotheprecedingproblembutIdonrsquotwantyoutojustjumpinandtypethisupIwantyoutotaketheroughskeletoncodeIdidandtrytomakeitworkbasedonthedescriptionOnceyouhaveyoursolutionthenyoucancomebackandseehowIdiditIrsquomgoingtobreakthisfinalfileex43pydownintosectionsandexplaineachoneratherthandumpallthecodeatonceClickheretoviewcodeimage

ex43py

1fromsysimportexit

2fromrandomimportrandint

3fromtextwrapimportdedentThisisjustourbasicimportsfor

thegameTheonlynewthingistheimportofthededentfunction

fromthetextwrapmoduleThislittlefunctionwillhelpuswriteour

roomdescriptionsusing(triple-quote)stringsItsimplystrips

leadingwhite-spacefromthebeginningsoflinesinastringWithout

thisfunctionusingstylestringsfailsbecausetheyare

indentedonthescreenthesamelevelasinthePythoncode

Clickheretoviewcodeimage

ex43py

1classScene(object)

2

3defenter(self)

4print(Thissceneisnotyetconfigured)

5print(Subclassitandimplemententer())

6exit(1)AsyousawintheskeletoncodeIhaveabase

classforScenethatwillhavethecommonthingsthatallscenesdo

Inthissimpleprogramtheydonrsquotdomuchsothisismorea

demonstrationofwhatyouwoulddotomakeabaseclass

Clickheretoviewcodeimage

ex43py

1classEngine(object)

2

3def__init__(selfscene_map)

4selfscene_map=scene_map

5

6defplay(self)

7current_scene=selfscene_mapopening_scene()

8last_scene=selfscene_mapnext_scene(finished)

9

10whilecurrent_scene=last_scene

11next_scene_name=current_sceneenter()

12current_scene=

selfscene_mapnext_scene(next_scene_name)

13

14besuretoprintoutthelastscene

15current_sceneenter()IalsohavemyEngineclassand

youcanseehowIrsquomalreadyusingthemethodsforMapopening_scene

andMapnext_sceneBecauseIrsquovedoneabitofplanningIcanjust

assumeIrsquollwritethoseandthenusethembeforeIrsquovewrittentheMap

class

Clickheretoviewcodeimage

ex43py

1classDeath(Scene)

2

3quips=[

4YoudiedYoukindasuckatthis

5YourMomwouldbeproudifsheweresmarter

6Suchaluser

7Ihaveasmallpuppythatsbetteratthis

8YoureworsethanyourDadsjokes

9

10]

11

12defenter(self)

13print(Deathquips[randint(0len(selfquips)-1)])

14exit(1)MyfirstsceneistheoddscenenamedDeath

whichshowsyouthesimplestkindofsceneyoucanwrite

Clickheretoviewcodeimage

ex43py

1classCentralCorridor(Scene)

2

3defenter(self)

4print(dedent(

5TheGothonsofPlanetPercal25haveinvadedyour

shipand

6destroyedyourentirecrewYouarethelast

surviving

7memberandyourlastmissionistogettheneutron

destruct

8bombfromtheWeaponsArmoryputitinthebridge

and

9blowtheshipupaftergettingintoanescapepod

10

11Yourerunningdownthecentralcorridortothe

Weapons

12ArmorywhenaGothonjumpsoutredscalyskin

darkgrimy

13teethandevilclowncostumeflowingaroundhis

hate

14filledbodyHesblockingthedoortotheArmory

and

15abouttopullaweapontoblastyou

16))

17

18action=input(gt)

19

20ifaction==shoot

21print(dedent(

22Quickonthedrawyouyankoutyourblaster

andfire

23itattheGothonHisclowncostumeis

flowingand

24movingaroundhisbodywhichthrowsoffyour

aim

25Yourlaserhitshiscostumebutmisseshim

entirely

26Thiscompletelyruinshisbrandnewcostume

hismother

27boughthimwhichmakeshimflyintoan

insanerage

28andblastyourepeatedlyinthefaceuntil

youare

29deadThenheeatsyou

30))

31returndeath

32

33elifaction==dodge

34print(dedent(

35Likeaworldclassboxeryoudodgeweave

slipand

36sliderightastheGothonsblastercranksa

laser

37pastyourheadInthemiddleofyourartful

dodge

38yourfootslipsandyoubangyourheadonthe

metal

39wallandpassoutYouwakeupshortlyafter

onlyto

40dieastheGothonstompsonyourheadand

eatsyou

41))

42returndeath

43

44elifaction==tellajoke

45print(dedent(

46LuckyforyoutheymadeyoulearnGothon

insultsin

47theacademyYoutelltheoneGothonjoke

youknow

48Lbhezbgurevffbsngjurafurfvgfnebhaq

gurubhfr

49furfvgfnebhaqgurubhfrTheGothonstops

tries

50nottolaughthenbustsoutlaughingand

cantmove

51Whileheslaughingyourunupandshoothim

squarein

52theheadputtinghimdownthenjumpthrough

the

53WeaponArmorydoor

54))

55returnlaser_weapon_armory

56

57else

58print(DOESNOTCOMPUTE)

59returncentral_corridor

AfterthatIrsquovecreatedtheCentralCorridorwhichisthestartofthegameIrsquomdoingthescenesforthegamebeforetheMapbecauseIneedtoreferencethemlaterYoushouldalsoseehowIusethededentfunctiononline4TryremovingitlatertoseewhatitdoesClickheretoviewcodeimage

ex43py

1classLaserWeaponArmory(Scene)

2

3defenter(self)

4print(dedent(

5YoudoadiverollintotheWeaponArmory

crouchandscan

6theroomformoreGothonsthatmightbe

hidingItsdead

7quiettooquietYoustandupandruntothe

farsideof

8theroomandfindtheneutronbombinits

container

9Theresakeypadlockontheboxandyouneed

thecodeto

10getthebomboutIfyougetthecodewrong10

timesthen

11thelockclosesforeverandyoucantgetthe

bombThe

12codeis3digits

13))

14

15code=frandint(19)randint(19)randint(19)

16guess=input([keypad]gt)

17guesses=0

18

19whileguess=codeandguesseslt10

20print(BZZZZEDDD)

21guesses+=1

22guess=input([keypad]gt)

23

24ifguess==code

25print(dedent(

26Thecontainerclicksopenandtheseal

breaksletting

27gasoutYougrabtheneutronbombandrun

asfastas

28youcantothebridgewhereyoumustplace

itinthe

29rightspot

30))

31returnthe_bridge

32else

33print(dedent(

34Thelockbuzzesonelasttimeandthenyou

heara

35sickeningmeltingsoundasthemechanismis

fused

36togetherYoudecidetositthereand

finallythe

37Gothonsblowuptheshipfromtheirshipand

youdie

38))

39returndeath

40

41

42

43classTheBridge(Scene)

44

45defenter(self)

46print(dedent(

47YouburstontotheBridgewiththenetron

destructbomb

48underyourarmandsurprise5Gothonswhoare

tryingto

49takecontroloftheshipEachofthemhasan

evenuglier

50clowncostumethanthelastTheyhavent

pulledtheir

51weaponsoutyetastheyseetheactivebomb

underyour

52armanddontwanttosetitoff

53))

54

55action=input(gt)

56

57ifaction==throwthebomb

58print(dedent(

59Inapanicyouthrowthebombatthegroup

ofGothons

60andmakealeapforthedoorRightasyou

dropita

61Gothonshootsyourightinthebackkilling

youAs

62youdieyouseeanotherGothonfrantically

tryto

63disarmthebombYoudieknowingtheywill

probably

64blowupwhenitgoesoff

65))

66returndeath

67

68elifaction==slowlyplacethebomb

69print(dedent(

70Youpointyourblasteratthebombunder

yourarmand

71theGothonsputtheirhandsupandstartto

sweat

72Youinchbackwardtothedooropenitand

then

73carefullyplacethebombonthefloor

pointingyour

74blasteratitYouthenjumpbackthrough

thedoor

75punchtheclosebuttonandblastthelockso

the

76GothonscantgetoutNowthatthebombis

placed

77youruntotheescapepodtogetoffthis

tincan

78))

79

80returnescape_pod

81else

82print(DOESNOTCOMPUTE)

83returnthe_bridge

84

85

86classEscapePod(Scene)

87

88defenter(self)

89print(dedent(

90Yourushthroughtheshipdesperatelytryingto

makeitto

91theescapepodbeforethewholeship

explodesItseems

92likehardlyanyGothonsareontheshipsoyour

runis

93clearofinterferenceYougettothechamber

withthe

94escapepodsandnowneedtopickoneto

takeSomeof

95themcouldbedamagedbutyoudonthavetimeto

look

96Theres5podswhichonedoyoutake

97))

98

99good_pod=randint(15)

100guess=input([pod]gt)

101

102

103ifint(guess)=good_pod

104print(dedent(

105Youjumpintopodguessandhittheeject

button

106Thepodescapesoutintothevoidofspace

then

107implodesasthehullrupturescrushingyour

bodyinto

108jamjelly

109))

110returndeath

111else

112print(dedent(

113Youjumpintopodguessandhittheeject

button

114Thepodeasilyslidesoutintospaceheading

tothe

115planetbelowAsitfliestotheplanet

youlook

116backandseeyourshipimplodethenexplode

likea

117brightstartakingouttheGothonshipat

thesame

118timeYouwon

119))

120

121returnfinished

122

123classFinished(Scene)

124

125defenter(self)

126print(YouwonGoodjob)

127returnfinished

ThisistherestofthegamersquosscenesandsinceIknowIneedthemandhavethoughtabouthowtheyrsquollflowtogetherIrsquomabletocodethemupdirectlyIncidentallyIwouldnrsquotjusttypeallthiscodeinRememberIsaidtotryandbuildthisincrementallyonelittlebitatatimeIrsquomjustshowingyouthefinalresultClickheretoviewcodeimage

ex43py

1classMap(object)

2

3scenes=

4central_corridorCentralCorridor()

5laser_weapon_armoryLaserWeaponArmory()

6the_bridgeTheBridge()

7escape_podEscapePod()

8deathDeath()

9finishedFinished()

10

11

12def__init__(selfstart_scene)

13selfstart_scene=start_scene

14

15defnext_scene(selfscene_name)

16val=Mapscenesget(scene_name)

17returnval

18

19defopening_scene(self)

20returnselfnext_scene(selfstart_scene)AfterthatI

havemyMapclassandyoucanseeitisstoringeachscenebyname

inadictionaryandthenIrefertothatdictwithMapscenesThis

isalsowhythemapcomesafterthescenesbecausethedictionaryhas

torefertothescenessotheyhavetoexist

Clickheretoviewcodeimage

ex43py

1a_map=Map(central_corridor)

2a_game=Engine(a_map)

3a_gameplay()FinallyIrsquovegotmycodethatrunsthegameby

makingaMapthenhandingthatmaptoanEnginebeforecallingplay

tomakethegamework

WhatYouShouldSeeMakesureyouunderstandthegameandthatyoutriedtosolveityourselffirstOnethingtodoifyoursquorestumpedischeatalittlebyreadingmycodethencontinuetryingtosolveityourselfWhenIrunmygameitlookslikethisClickheretoviewcodeimage

Exercise43Session

$python36ex43py

TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyedyourentirecrewYouarethelastsurviving

memberandyourlastmissionistogettheneutrondestruct

bombfromtheWeaponsArmoryputitinthebridgeand

blowtheshipupaftergettingintoanescapepod

YourerunningdownthecentralcorridortotheWeapons

ArmorywhenaGothonjumpsoutredscalyskindarkgrimy

teethandevilclowncostumeflowingaroundhishate

filledbodyHesblockingthedoortotheArmoryand

abouttopullaweapontoblastyou

gtdodge

Likeaworldclassboxeryoudodgeweaveslipand

sliderightastheGothonsblastercranksalaser

pastyourheadInthemiddleofyourartfuldodge

yourfootslipsandyoubangyourheadonthemetal

wallandpassoutYouwakeupshortlyafteronlyto

dieastheGothonstompsonyourheadandeatsyou

YoureworsethanyourDadsjokes

StudyDrills1ChangeitMaybeyouhatethisgameItcouldbetooviolentormaybeyouarenrsquotintosci-fiGetthegameworkingthenchangeittowhatyoulikeThisisyourcomputeryoumakeitdowhatyouwant

2IhaveabuginthiscodeWhyisthedoorlockguessing11times3Explainhowreturningthenextroomworks4AddcheatcodestothegamesoyoucangetpastthemoredifficultroomsIcandothiswithtwowordsononeline

5GobacktomydescriptionandanalysisthentrytobuildasmallcombatsystemfortheheroandthevariousGothonsheencounters

6ThisisactuallyasmallversionofsomethingcalledaldquofinitestatemachinerdquoReadaboutthemTheymightnotmakesensebuttryanyway

CommonStudentQuestionsWherecanIfindstoriesformyowngamesYoucanmakethemupjustlikeyouwouldtellastorytoafriendOryoucantakesimplescenesfromabookormovieyoulike

Exercise44InheritanceversusComposition

InthefairytalesaboutheroesdefeatingevilvillainstherersquosalwaysadarkforestofsomekindItcouldbeacaveaforestanotherplanetjustsomeplacethateveryoneknowstheheroshouldnrsquotgoOfcourseshortlyafterthevillainisintroducedyoufindoutyestheherohastogotothatstupidforesttokillthebadguyItseemstheherojustkeepsgettingintosituationsthatrequirehimtoriskhislifeinthisevilforestYourarelyreadfairytalesabouttheheroeswhoaresmartenoughtojustavoidthewholesituationentirelyYouneverhearaherosayldquoWaitaminuteifIleavetomakemyfortunesonthehighseasleavingButtercupbehindIcoulddieandthenshersquodhavetomarrysomeuglyprincenamedHumperdinkHumperdinkIthinkIrsquollstayhereandstartaFarmBoyforRentbusinessrdquoIfhedidthattherersquodbenofireswampdyingreanimationswordfightsgiantsoranykindofstoryreallyBecauseofthistheforestinthesestoriesseemstoexistlikeablackholethatdragstheheroinnomatterwhattheydoInobject-orientedprogramminginheritanceistheevilforestExperiencedprogrammersknowtoavoidthisevilbecausetheyknowthatdeepinsidetheDarkForestInheritanceistheEvilQueenMultipleInheritanceShelikestoeatsoftwareandprogrammerswithhermassivecomplexityteethchewingonthefleshofthefallenButtheforestissopowerfulandsotemptingthatnearlyeveryprogrammerhastogointoitandtrytomakeitoutalivewiththeEvilQueenrsquosheadbeforetheycancallthemselvesrealprogrammersYoujustcanrsquotresisttheInheritanceForestrsquospullsoyougoinAftertheadventureyoulearntojuststayoutofthatstupidforestandbringanarmyifyouareeverforcedtogoinagainThisisbasicallyafunnywaytosaythatIrsquomgoingtoteachyousomethingyoushouldusecarefullycalledinheritanceProgrammerswhoarecurrentlyintheforestbattlingtheQueenwillprobablytellyouthatyouhavetogoinTheysaythisbecausetheyneedyourhelpsincewhattheyrsquovecreatedisprobablytoomuchforthemtohandleButyoushouldalwaysrememberthisMostoftheusesofinheritancecanbesimplifiedorreplacedwithcompositionandmultipleinheritanceshouldbeavoidedatallcosts

WhatIsInheritanceInheritanceisusedtoindicatethatoneclasswillgetmostorallofitsfeaturesfromaparentclassThishappensimplicitlywheneveryouwriteclass

Foo(Bar)whichsaysldquoMakeaclassFoothatinheritsfromBarrdquoWhenyoudothisthelanguagemakesanyactionthatyoudooninstancesofFooalsoworkasiftheyweredonetoaninstanceofBarDoingthisletsyouputcommonfunctionalityintheBarclassthenspecializethatfunctionalityintheFooclassasneededWhenyouaredoingthiskindofspecializationtherearethreewaysthattheparentandchildclassescaninteract1Actionsonthechildimplyanactionontheparent

2Actionsonthechildoverridetheactionontheparent3Actionsonthechildaltertheactionontheparent

Iwillnowdemonstrateeachoftheseinorderandshowyoucodeforthem

ImplicitInheritanceFirstIwillshowyoutheimplicitactionsthathappenwhenyoudefineafunctionintheparentbutnotinthechildClickheretoviewcodeimage

ex44apy

1classParent(object)

2

3defimplicit(self)

4print(PARENTimplicit())

5

6classChild(Parent)

7pass

8

9dad=Parent()

10son=Child()

11

12dadimplicit()

13sonimplicit()TheuseofpassundertheclassChildishow

youtellPythonthatyouwantanemptyblockThiscreatesaclass

namedChildbutsaysthattherersquosnothingnewtodefineinit

InsteaditwillinheritallofitsbehaviorfromParentWhenyourun

thiscodeyougetthefollowingExercise44aSession

$python36ex44apy

PARENTimplicit()

PARENTimplicit()NoticehoweventhoughIrsquomcallingsonimplicit()

online13andeventhoughChilddoesnothaveanimplicitfunction

defineditstillworksanditcallstheonedefinedinParentThis

showsyouthatifyouputfunctionsinabaseclass(ieParent)

thenallsubclasses(ieChild)willautomaticallygetthose

featuresVeryhandyforrepetitivecodeyouneedinmanyclasses

OverrideExplicitlyTheproblemwithhavingfunctionscalledimplicitlyissometimesyouwantthechildtobehavedifferentlyInthiscaseyouwanttooverridethefunctioninthechildeffectivelyreplacingthefunctionalityTodothisjustdefineafunctionwiththesamenameinChildHerersquosanexampleClickheretoviewcodeimage

ex44bpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6classChild(Parent)

7

8defoverride(self)

9print(CHILDoverride())

10

11dad=Parent()

12son=Child()

13

14dadoverride()

15sonoverride()InthisexampleIhaveafunctionnamedoverride

inbothclassessoletrsquosseewhathappenswhenIrunit

Exercise44bSession

$python36ex44bpy

PARENToverride()

CHILDoverride()Asyoucanseewhenline14runsitrunsthe

Parentoverridefunctionbecausethatvariable(dad)isaParentBut

whenline15runsitprintsouttheChildoverridemessagesbecause

sonisaninstanceofChildandChildoverridesthatfunctionby

definingitsownversion

Takeabreakrightnowandtryplayingwiththesetwoconceptsbeforecontinuing

AlterBeforeorAfter

AlterBeforeorAfterThethirdwaytouseinheritanceisaspecialcaseofoverridingwhereyouwanttoalterthebehaviorbeforeoraftertheParentclassrsquosversionrunsYoufirstoverridethefunctionjustlikeinthelastexamplebutthenyouuseaPythonbuilt-infunctionnamedsupertogettheParentversiontocallHerersquostheexampleofdoingthatsoyoucanmakesenseofthisdescriptionClickheretoviewcodeimage

ex44cpy

1classParent(object)

2

3defaltered(self)

4print(PARENTaltered())

5

6classChild(Parent)

7

8defaltered(self)

9print(CHILDBEFOREPARENTaltered())

10super(Childself)altered()

11print(CHILDAFTERPARENTaltered())

12

13dad=Parent()

14son=Child()

15

16dadaltered()

17sonaltered()Theimportantlineshereare9ndash11whereinthe

ChildIdothefollowingwhensonaltered()iscalled1Because

IrsquoveoverriddenParentalteredtheChildalteredversionrunsand

line9executeslikeyoursquodexpect

2InthiscaseIwanttodoabeforeandaftersoafterline9IwanttousesupertogettheParentalteredversion

3Online10Icallsuper(Childself)altered()whichisawareofinheritanceandwillgettheParentclassforyouYoushouldbeabletoreadthisasldquocallsuperwithargumentsChildandselfthencallthefunctionalteredonwhateveritreturnsrdquo

4AtthispointtheParentalteredversionofthefunctionrunsandthatprintsouttheParentmessage

5FinallythisreturnsfromtheParentalteredandtheChildalteredfunctioncontinuestoprintouttheaftermessage

IfyourunthisyoushouldseethisClickheretoviewcodeimage

Exercise44cSession

$python36ex44cpy

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

AllThreeCombinedTodemonstratealloftheseIhaveafinalversionthatshowseachkindofinteractionfrominheritanceinonefileClickheretoviewcodeimage

ex44dpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6defimplicit(self)

7print(PARENTimplicit())

8

9defaltered(self)

10print(PARENTaltered())

11

12classChild(Parent)

13

14defoverride(self)

15print(CHILDoverride())

16

17defaltered(self)

18print(CHILDBEFOREPARENTaltered())

19super(Childself)altered()

20print(CHILDAFTERPARENTaltered())

21

22dad=Parent()

23son=Child()

24

25dadimplicit()

26sonimplicit()

27

28dadoverride()

29sonoverride()

30

31dadaltered()

32sonaltered()Gothrougheachlineofthiscodeandwritea

commentexplainingwhatthatlinedoesandwhetheritrsquosanoverride

ornotThenrunitandconfirmyougetwhatyouexpectedClickhere

toviewcodeimage

Exercise44dSession

$python36ex44dpy

PARENTimplicit()

PARENTimplicit()

PARENToverride()

CHILDoverride()

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

TheReasonforsuper()ThisshouldseemlikecommonsensebutthenwegetintotroublewithathingcalledmultipleinheritanceMultipleinheritanceiswhenyoudefineaclassthatinheritsfromoneormoreclasseslikethisClickheretoviewcodeimage

classSuperFun(ChildBadStuff)

passThisislikesayingldquoMakeaclassnamedSuperFunthat

inheritsfromtheclassesChildandBadStuffatthesametimerdquo

InthiscasewheneveryouhaveimplicitactionsonanySuperFuninstancePythonhastolookupthepossiblefunctionintheclasshierarchyforbothChildandBadStuffbutitneedstodothisinaconsistentorderTodothisPythonusesldquomethodresolutionorderrdquo(MRO)andanalgorithmcalledC3togetitstraightBecausetheMROiscomplexandawell-definedalgorithmisusedPythoncanrsquotleaveittoyoutogettheMROrightInsteadPythongivesyouthesuper()functionwhichhandlesallofthisforyouintheplacesthatyouneedthealteringtypeofactionsasIdidinChildalteredWithsuper()youdonrsquothavetoworryaboutgettingthisrightandPythonwillfindtherightfunctionforyou

Usingsuper()with__init__Themostcommonuseofsuper()isactuallyin__init__functionsinbaseclassesThisisusuallytheonlyplacewhereyouneedtodosomethingsina

childthencompletetheinitializationintheparentHerersquosaquickexampleofdoingthatintheChildClickheretoviewcodeimage

classChild(Parent)

def__init__(selfstuff)

selfstuff=stuff

super(Childself)__init__()Thisisprettymuchthesameas

theChildalteredexampleaboveexceptIrsquomsettingsomevariablesin

the__init__beforehavingtheParentinitializewithits

Parent__init__

CompositionInheritanceisusefulbutanotherwaytodotheexactsamethingisjusttouseotherclassesandmodulesratherthanrelyonimplicitinheritanceIfyoulookatthethreewaystoexploitinheritancetwoofthethreeinvolvewritingnewcodetoreplaceoralterfunctionalityThiscaneasilybereplicatedbyjustcallingfunctionsinamoduleHerersquosanexampleofdoingthisClickheretoviewcodeimage

ex44epy

1classOther(object)

2

3defoverride(self)

4print(OTHERoverride())

5

6defimplicit(self)

7print(OTHERimplicit())

8

9defaltered(self)

10print(OTHERaltered())

11

12classChild(object)

13

14def__init__(self)

15selfother=Other()

16

17defimplicit(self)

18selfotherimplicit()

19

20defoverride(self)

21print(CHILDoverride())

22

23defaltered(self)

24print(CHILDBEFOREOTHERaltered())

25selfotheraltered()

26print(CHILDAFTEROTHERaltered())

27

28son=Child()

29

30sonimplicit()

31sonoverride()

32sonaltered()InthiscodeIrsquomnotusingthenameParentsince

thereisnotaparent-childis-arelationshipThisisahas-a

relationshipwhereChildhas-aOtherthatitusestogetitswork

doneWhenIrunthisIgetthefollowingoutputExercise44e

Session

$python36ex44epy

OTHERimplicit()

CHILDoverride()

CHILDBEFOREOTHERaltered()

OTHERaltered()

CHILDAFTEROTHERaltered()Youcanseethatmostofthecodein

ChildandOtheristhesametoaccomplishthesamethingTheonly

differenceisthatIhadtodefineaChildimplicitfunctiontodo

thatoneactionIcouldthenaskmyselfifIneedthisOthertobea

classandcouldIjustmakeitintoamodulenamedotherpy

WhentoUseInheritanceorCompositionThequestionofldquoinheritanceversuscompositionrdquocomesdowntoanattempttosolvetheproblemofreusablecodeYoudonrsquotwanttohaveduplicatedcodealloveryoursoftwaresincethatrsquosnotcleanandefficientInheritancesolvesthisproblembycreatingamechanismforyoutohaveimpliedfeaturesinbaseclassesCompositionsolvesthisbygivingyoumodulesandthecapabilitytocallfunctionsinotherclassesIfbothsolutionssolvetheproblemofreusethenwhichoneisappropriateinwhichsituationsTheanswerisincrediblysubjectivebutIrsquollgiveyoumythreeguidelinesforwhentodowhich1AvoidmultipleinheritanceatallcostsasitrsquostoocomplextobereliableIfyoursquorestuckwithitthenbepreparedtoknowtheclasshierarchyandspendtimefindingwhereeverythingiscomingfrom

2Usecompositiontopackagecodeintomodulesthatareusedinmanydifferentunrelatedplacesandsituations

3Useinheritanceonlywhenthereareclearlyrelatedreusablepiecesofcodethatfitunderasinglecommonconceptorifyouhavetobecauseofsomethingyoursquoreusing

DonotbeaslavetotheserulesThethingtorememberaboutobject-orientedprogrammingisthatitisentirelyasocialconventionprogrammershavecreatedtopackageandsharecodeBecauseitrsquosasocialconventionbutonethatrsquoscodifiedinPythonyoumaybeforcedtoavoidtheserulesbecauseofthepeopleyouworkwithInthatcasefindouthowtheyusethingsandthenjustadapttothesituation

StudyDrillsThereisonlyoneStudyDrillforthisexercisebecauseitisabigexerciseGoandreadhttpwwwpythonorgdevpepspep-0008andstarttryingtouseitinyourcodeYoursquollnoticethatsomeofitisdifferentfromwhatyoursquovebeenlearninginthisbookbutnowyoushouldbeabletounderstandtheirrecommendationsandusetheminyourowncodeTherestofthecodeinthisbookmayormaynotfollowtheseguidelinesdependingonwhetheritmakesthecodemoreconfusingIsuggestyoualsodothisascomprehensionismoreimportantthanimpressingeveryonewithyourknowledgeofesotericstylerules

CommonStudentQuestionsHowdoIgetbetteratsolvingproblemsthatIhavenrsquotseenbeforeTheonlywaytogetbetteratsolvingproblemsistosolveasmanyproblemsasyoucanbyyourselfTypicallypeoplehitadifficultproblemandthenrushouttofindananswerThisisfinewhenyouhavetogetthingsdonebutifyouhavethetimetosolveityourselfthentakethattimeStopandbangyourheadagainsttheproblemforaslongaspossibletryingeverypossiblethinguntilyousolveitorgiveupAfterthattheanswersyoufindwillbemoresatisfyingandyoursquolleventuallygetbetteratsolvingproblems

ArenrsquotobjectsjustcopiesofclassesInsomelanguages(likeJavaScript)thatistrueThesearecalledprototypelanguagesandtherearenotmanydifferencesbetweenobjectsandclassesotherthanusageInPythonhoweverclassesactastemplatesthatldquomintrdquonewobjectssimilartohowcoinsaremintedusingadie(template)

Exercise45YouMakeaGame

YouneedtostartlearningtofeedyourselfHopefullyasyouhaveworkedthroughthisbookyouhavelearnedthatalltheinformationyouneedisontheinternetYoujusthavetogosearchforitTheonlythingyouhavebeenmissingaretherightwordsandwhattolookforwhenyousearchNowyoushouldhaveasenseofitsoitrsquosabouttimeyoustruggledthroughabigprojectandtriedtogetitworkingHereareyourrequirements

1MakeadifferentgamefromtheoneImade2UsemorethanonefileanduseimporttousethemMakesureyouknowwhatthatis

3Useoneclassperroomandgivetheclassesnamesthatfittheirpurposes(likeGoldRoomKoiPondRoom)

4YourrunnerwillneedtoknowabouttheseroomssomakeaclassthatrunsthemandknowsaboutthemTherersquoreplentyofwaystodothisbutconsiderhavingeachroomreturnwhatroomisnextorsettingavariableofwhatroomisnext

OtherthanthatIleaveittoyouSpendawholeweekonthisandmakeitthebestgameyoucanUseclassesfunctionsdictslistsanythingyoucantomakeitniceThepurposeofthislessonistoteachyouhowtostructureclassesthatneedotherclassesinsideotherfilesRememberIrsquomnottellingyouexactlyhowtodothisbecauseyouhavetodothisyourselfGofigureitoutProgrammingisproblemsolvingandthatmeanstryingthingsexperimentingfailingscrappingyourworkandtryingagainWhenyougetstuckaskforhelpandshowpeopleyourcodeIftheyaremeantoyouignorethemandfocusonthepeoplewhoarenotmeanandoffertohelpKeepworkingitandcleaningituntilitrsquosgoodthenshowitsomemoreGoodluckandseeyouinaweekwithyourgame

EvaluatingYourGameInthisexerciseyouwillevaluatethegameyoujustmadeMaybeyougotpartwaythroughitandyougotstuckMaybeyougotitworkingbutjustbarelyEitherwaywersquoregoingtogothroughabunchofthingsyoushouldknownowandmakesureyoucoveredtheminyourgameWersquoregoingtostudyproperlyformattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquo

formattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquoknowledgeWhywouldIhaveyoutrytodoityourselfandthenshowyouhowtodoitrightFromnowoninthebookIrsquomgoingtotrytomakeyouself-sufficientIrsquovebeenholdingyourhandmostlythiswholetimeandIcanrsquotdothatformuchlongerIrsquomnowinsteadgoingtogiveyouthingstodohaveyoudothemonyourownandthengiveyouwaystoimprovewhatyoudidYouwillstruggleatfirstandprobablybeveryfrustratedbutstickwithitandeventuallyyouwillbuildamindforsolvingproblemsYouwillstarttofindcreativesolutionstoproblemsratherthanjustcopysolutionsoutoftextbooks

FunctionStyleAlltheotherrulesIrsquovetaughtyouabouthowtomakeanicefunctionapplyherebutaddthesethings

bullForvariousreasonsprogrammerscallfunctionsthatarepartofclassesldquomethodsrdquoItrsquosmostlymarketingbutjustbewarnedthateverytimeyousayldquofunctionrdquotheyrsquollannoyinglycorrectyouandsayldquomethodrdquoIftheygettooannoyingjustaskthemtodemonstratethemathematicalbasisthatdetermineshowaldquomethodrdquoisdifferentfromaldquofunctionrdquoandtheyrsquollshutup

bullWhenyouworkwithclassesmuchofyourtimeisspenttalkingaboutmakingtheclassldquodothingsrdquoInsteadofnamingafunctionafterwhatthefunctiondoesinsteadnameitasifitrsquosacommandyouaregivingtotheclassForexamplepopissayingldquoHeylistpopthisoffrdquoItisnrsquotcalledremove_from_end_of_listbecauseeventhoughthatrsquoswhatitdoesthatrsquosnotacommandtoalist

bullKeepyourfunctionssmallandsimpleForsomereasonwhenpeoplestartlearningaboutclassestheyforgetthis

ClassStylebullYourclassshoulduseldquocamelcaserdquoasinSuperGoldFactoryratherthanldquounderscoreformatrdquoasinsuper_gold_factory

bullTrynottodotoomuchinyour__init__functionsItmakesthemhardertouse

bullYourotherfunctionsshoulduseunderscoreformatsowritemy_awesome_hairandnotmyawesomehairorMyAwesomeHair

bullBeconsistentinhowyouorganizeyourfunctionargumentsIfyourclass

hastodealwithusersdogsandcatskeepthatorderthroughoutunlessitreallydoesnrsquotmakesenseIfyouhaveonefunctionthattakes(dogcatuser)andtheothertakes(usercatdog)itrsquollbehardtouse

bullTrynottousevariablesthatcomefromthemoduleorglobalsTheyshouldbefairlyself-contained

bullAfoolishconsistencyisthehobgoblinoflittlemindsConsistencyisgoodbutfoolishlyfollowingsomeidioticmantrabecauseeveryoneelsedoesisbadstyleThinkforyourself

bullAlwaysalwayshaveclassName(object)formatorelseyouwillbeinbigtrouble

CodeStylebullGiveyourcodeverticalspacesopeoplecanreaditYouwillfindsomeverybadprogrammerswhoareabletowritereasonablecodebutwhodonotaddanyspacesThisisbadstyleinanylanguagebecausethehumaneyeandbrainusespaceandverticalalignmenttoscanandseparatevisualelementsNothavingspaceisthesameasgivingyourcodeanawesomecamouflagepaintjob

bullIfyoucanrsquotreaditoutlouditrsquosprobablyhardtoreadIfyouarehavingaproblemmakingsomethingeasytousetryreadingitoutloudNotonlydoesthisforceyoutoslowdownandreallyreaditbutitalsohelpsyoufinddifficultpassagesandthingstochangeforreadability

bullTrytodowhatotherpeoplearedoinginPythonuntilyoufindyourownstyle

bullOnceyoufindyourownstyledonotbeajerkaboutitWorkingwithotherpeoplersquoscodeispartofbeingaprogrammerandotherpeoplehavereallybadtasteTrustmeyouwillprobablyhavereallybadtastetooandnotevenrealizeit

bullIfyoufindsomeonewhowritescodeinastyleyouliketrywritingsomethingthatmimicsthatstyle

GoodCommentsbullProgrammerswilltellyouthatyourcodeshouldbereadableenoughthatyoudonotneedcommentsTheyrsquollthentellyouintheirmostofficialsoundingvoiceldquoErgooneshouldneverwritecommentsordocumentationQEDrdquoThoseprogrammersareeitherconsultantswhogetpaidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendto

paidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendtoneverworkwithotherpeopleIgnorethemandwritecomments

bullWhenyouwritecommentsdescribewhyyouaredoingwhatyouaredoingThecodealreadysayshowsowhyyoudidthingsthewayyoudidismoreimportant

bullWhenyouwritedoccommentsforyourfunctionsmakethecommentsdocumentationforsomeonewhowillhavetouseyourcodeYoudonothavetogocrazybutanicelittlesentenceaboutwhatsomeonecandowiththatfunctionhelpsalot

bullWhilecommentsaregoodtoomanyarebadandyouhavetomaintainthemKeepyourcommentsrelativelyshortandtothepointandifyouchangeafunctionreviewthecommenttomakesureitrsquosstillcorrect

EvaluateYourGameIwantyoutonowpretendyouaremeAdoptaverysternlookprintoutyourcodeandtakearedpenandmarkeverymistakeyoufindincludinganythingfromthisexerciseandfromotherguidelinesyoursquovereadsofarOnceyouaredonemarkingyourcodeupIwantyoutofixeverythingyoucameupwithThenrepeatthisacoupleoftimeslookingforanythingthatcouldbebetterUseallthetricksIrsquovegivenyoutobreakyourcodedownintothesmallesttiniestlittleanalysisyoucanThepurposeofthisexerciseistotrainyourattentiontodetailonclassesOnceyouaredonewiththisbitofcodefindsomeoneelsersquoscodeanddothesamethingGothroughaprintedcopyofsomepartofitandpointoutallthemistakesandstyleerrorsyoufindThenfixitandseeifyourfixescanbedonewithoutbreakingthatprogramIwantyoutodonothingbutevaluateandfixcodefortheweekmdashyourowncodeandotherpeoplersquosItrsquollbeprettyhardworkbutwhenyouaredoneyourbrainwillbewiredtightlikeaboxerrsquoshands

Exercise46AProjectSkeleton

ThiswillbewhereyoustartlearninghowtosetupagoodprojectldquoskeletonrdquodirectoryThisskeletondirectorywillhaveallthebasicsyouneedtogetanewprojectupandrunningItwillhaveyourprojectlayoutautomatedtestsmodulesandinstallscriptsWhenyougotomakeanewprojectjustcopythisdirectorytoanewnameandeditthefilestogetstarted

macOSLinuxSetupBeforeyoucanbeginthisexerciseyouneedtoinstallsomesoftwareforPythonbyusingatoolcalledpip36(orjustpip)toinstallnewmodulesThepip36commandshouldbeincludedwithyourpython36installationYoursquollwanttoverifythisusingthiscommand

$pip36list

pip(901)

setuptools(2880)

$

YoucanignoreanydeprecationwarningifyouseeitYoumayalsoseeothertoolsinstalledbutthebaseshouldbepipandsetuptoolsOnceyoursquoveverifiedthisyoucantheninstallvirtualenvClickheretoviewcodeimage

$sudopip36installvirtualenv

Password

Collectingvirtualenv

Downloadingvirtualenvndash1510ndashpy2py3ndashnonendashanywhl(18MB)

100|||||||||||||||||||||||||||||||||18MB11MBs

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

$

ThisisforLinuxormacOSsystemsIfyoursquoreonLinuxmacOSyoursquollwanttorunthefollowingcommandtomakesureyouusethecorrectvirtualenvClickheretoviewcodeimage

$whereisvirtualenv

LibraryFrameworksPythonframeworkVersions36binvirtualenv

YoushouldseesomethingliketheaboveonmacOSbutLinuxwillbevariableOnLinuxyoumighthaveanactualvirtualenv36commandoryoumay

bebetteroffinstallingapackageforitfromyourpackagemanagementsystemOnceyoursquoveinstalledvirtualenvyoucanuseittocreatealdquofakerdquoPythoninstallationwhichmakesiteasiertomanageversionsofyourpackagesfordifferentprojectsFirstrunthiscommandandIrsquollexplainwhatitrsquosdoingClickheretoviewcodeimage

$mkdir~venvs

$virtualenvndashndashsystemndashsitendashpackages~venvslpthw

$~venvslpthwbinactivate

(lpthw)$

Herersquoswhatrsquosgoingonlinebyline1YoucreateadirectorycalledvenvsinyourHOME~tostoreallyourvirtualenvironments

2Yourunvirtualenvandtellittoincludethesystemsitepackages(--system-site-packages)theninstructittobuildthevirtualenvin~venvslpthw

3Youthenldquosourcerdquothelpthwvirtualenvironmentbyusingtheoperatorinbashfollowedbythe~venvslpthwbinactivatescript

4Finallyyourpromptchangestoinclude(lpthw)soyouknowthatyoursquoreusingthatvirtualenvironment

NowyoucanseewherethingsareinstalledClickheretoviewcodeimage

(lpthw)$whichpython

Userszedshawvenvslpthwbinpython

(lpthw)$python

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

(lpthw)$

YoucanseethatthepythonthatgetsrunisinstalledintheUserszedshawvenvslpthwbinpythondirectoryinsteadoftheoriginallocationThisalsosolvestheproblemofhavingtotypepython36sinceitinstallsbothClickheretoviewcodeimage

$whichpython36

Userszedshawvenvslpthwbinpython36

(lpthw)$

YoursquollfindthesamethingforvirtualenvandpipcommandsThefinalstepinthissetupistoinstallnoseatestingframeworkwersquolluseinthisexerciseClickheretoviewcodeimage

$pipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB32MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)$

Windows10SetupTheWindows10installisalittlesimplerthanonLinuxormacOSbutonlyifyouhaveoneversionofPythoninstalledIfyouhavebothPython36andPython27installedthenyouareonyourownasitismuchtoodifficulttomanagemultipleinstallationsIfyouhavefollowedthebooksofarandhaveonlyPython36thenherersquoswhatyoudoFirstchangetoyourhomedirectoryandconfirmyoursquorerunningtherightversionofpythonClickheretoviewcodeimage

gtcd~

gtpython

Python360(v36041df79263a11Dec232016080612)

[MSCv190064bit(AMD64)]onwin32

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

Thenyoursquollwanttorunpiptoconfirmyouhaveabasicinstall

gtpiplist

pip(901)

setuptools(2880)

YoucansafelyignoreanydeprecationwarninganditrsquosalrightifyouhaveotherpackagesinstalledNextyoursquollinstallvirtualenvforsettingupsimplevirtualenvironmentsfortherestofthebookClickheretoviewcodeimage

gtpipinstallvirtualenv

Collectingvirtualenv

Usingcachedvirtualenvndash1510ndashpy2py3ndashnonendashanywhl

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

OnceyouhavevirtualenvinstalledyoursquollneedtomakeavenvsdirectoryandfillitwithavirtualenvironmentClickheretoviewcodeimage

gtmkdirvenvs

gtvirtualenvndashndashsystemndashsitendashpackagesvenvslpthw

Usingbaseprefix

cuserszedshappdatalocalprogramspythonpython36

Newpythonexecutablein

CUserszedshawvenvslpthwScriptspythonexe

Installingsetuptoolspipwheeldone

ThosetwocommandscreateavenvsfolderforstoringdifferentvirtualenvironmentsandthencreateyourfirstonenamedlpthwAvirtualenvironment(virtualenv)isaldquofakerdquoplacetoinstallsoftwaresothatyoucanhavedifferentversionsofdifferentpackagesforeachprojectyoursquoreworkingonOnceyouhavethevirtualenvsetupyouneedtoactivateitClickheretoviewcodeimage

gtvenvslpthwScriptsactivate

ThatwillruntheactivatescriptforPowerShellwhichconfiguresthelpthwvirtualenvforyourcurrentshellEverytimeyouwanttouseyoursoftwareforthebookyoursquollrunthiscommandYoursquollnoticeinournextcommandthatthereisnowa(lpthw)addedtothePowerShellpromptshowingyouwhichvirtualenvyoursquoreusingFinallyyoujustneedtoinstallnoseforrunningtestslaterClickheretoviewcodeimage

(lpthw)gtpipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB12MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)gt

YoursquollseethatthisinstallsnoseexceptpipwillinstallitintoyourvenvslpthwvirtualenvironmentinsteadofthemainsystempackagesdirectoryThisletsyouinstallconflictingversionsofPythonpackagesforeachprojectyouworkonwithoutinfectingyourmainsystemconfiguration

CreatingtheSkeletonProjectDirectoryFirstcreatethestructureofyourskeletondirectorywiththesecommands

$mkdirprojects

$cdprojects

$mkdirskeleton

$cdskeleton

$mkdirbinNAMEtestsdocs

IuseadirectorynamedprojectstostoreallthevariousthingsIrsquomworkingonInsidethatdirectoryIhavemyskeletondirectorythatIputthebasisofmyprojectsintoThedirectoryNAMEwillberenamedtowhateveryouarecallingyourprojectrsquosmainmodulewhenyouusetheskeletonNextweneedtosetupsomeinitialfilesHerersquoshowyoudothatonLinuxmacOS

$touchNAME__init__py

$touchtests__init__py

HerersquosthesamethingonWindowsPowerShellClickheretoviewcodeimage

$newndashitemndashtypefileNAME__init__py

$newndashitemndashtypefiletests__init__py

ThatcreatesanemptyPythonmoduledirectorywecanputourcodeinThenweneedtocreateasetuppyfilewecanusetoinstallourprojectlaterifwewantClickheretoviewcodeimage

setuppy

1try

2fromsetuptoolsimportsetup

3exceptImportError

4fromdistutilscoreimportsetup

5

6config=

7descriptionMyProject

8authorMyName

9urlURLtogetitat

10download_urlWheretodownloadit

11author_emailMyemail

12version01

13install_requires[nose]

14packages[NAME]

15scripts[]

16nameprojectname

17

18

19setup(config)

EditthisfilesothatithasyourcontactinformationandisreadytogoforwhenyoucopyitFinallyyouwillwantasimpleskeletonfilefortestsnamedtestsNAME_testspyClickheretoviewcodeimage

NAME_testspy

1fromnosetoolsimport

2importNAME

3

4defsetup()

5print(SETUP)

6

7defteardown()

8print(TEARDOWN)

9

10deftest_basic()

11print(IRAN)

FinalDirectoryStructureWhenyouaredonesettingallofthisupyourdirectoryshouldlooklikeminehere

skeleton

NAME

__init__py

bin

docs

setuppy

tests

NAME_testspy

__init__py

AndfromnowonyoushouldrunyourcommandsfromthisdirectoryIfyoucanrsquotdols-RandifyoudonrsquotseethissamestructurethenyouareinthewrongplaceForexamplepeoplecommonlygointothetestsdirectoryto

trytorunfilestherewhichwonrsquotworkTorunyourapplicationrsquostestsyouwouldneedtobeabovetestsandthislocationIhaveaboveSoifyoutrythisClickheretoviewcodeimage

$cdtestsWRONGWRONGWRONG

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran0testsin0000s

OK

ThatiswrongYouhavetobeabovetestssoassumingyoumadethismistakeyouwouldfixitbydoingthisClickheretoviewcodeimage

$cdgetoutoftests

$lsCORRECTyouarenowintherightspot

NAMEbindocssetuppytests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0004s

OK

Rememberthisbecausepeoplemakethismistakequitefrequently

WarningAtthetimeofpublicationIlearnedthatthenoseprojecthasbeenabandonedandmightnotworkwellIfyouhavestrangesyntaxerrorswhenyourunnoseteststhenlookattheerroroutputIfitreferencesldquopython27rdquointheoutputthenchancesarenosetestsistryingtorunthe27versionofPythononyourcomputerThesolutionistorunnoseusingpython36-mnoseonLinuxormacOSOnWindowsyoumaynothavethisproblembutusingpython-mnosewillsolveitifyoudo

TestingYourSetupAfteryougetallthatinstalledyoushouldbeabletodothis

$nosetests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0007s

OK

IrsquollexplainwhatthisnoseteststhingisdoinginthenextexercisebutfornowifyoudonotseethatyouprobablygotsomethingwrongMakesureyouput__init__pyfilesinyourNAMEandtestsdirectoriesandmakesureyougottestsNAME_testspyright

UsingtheSkeletonYouarenowdonewithmostofyouryakshavingWheneveryouwanttostartanewprojectjustdothis

1MakeacopyofyourskeletondirectoryNameitafteryournewproject2Rename(move)theNAMEdirectorytobethenameofyourprojectorwhateveryouwanttocallyourrootmodule

3Edityoursetuppytohavealltheinformationforyourproject4RenametestsNAME_testspytoalsohaveyourmodulename5Doublecheckitrsquosallworkingbyusingnosetestsagain6Startcoding

RequiredQuizThisexercisedoesnrsquothaveStudyDrillsinsteadherersquosquizyoushouldcomplete

1Readabouthowtouseallofthethingsyouinstalled2ReadaboutthesetuppyfileandallithastoofferWarningItisnotaverywell-writtenpieceofsoftwaresoitwillbeverystrangetouse

3Makeaprojectandstartputtingcodeintothemodulethengetthemoduleworking

4PutascriptinthebindirectorythatyoucanrunReadabouthowyoucanmakeaPythonscriptthatrsquosrunnableforyoursystem

5Mentionthebinscriptyoucreatedinyoursetuppysothatitgetsinstalled

6Useyoursetuppytoinstallyourownmoduleandmakesureitworksthenusepiptouninstallit

CommonStudentQuestions

CommonStudentQuestionsDotheseinstructionsworkonWindowsTheyshouldbutdependingontheversionofWindowsyoumayneedtostrugglewiththesetupabittogetitworkingJustkeepresearchingandtryingituntilyougetitorseeifyoucanaskamoreexperiencedPython+Windowsfriendtohelpout

WhatdoIputintheconfigdictionaryinmysetuppyMakesureyoureadthedocumentationfordistutilsathttpdocspythonorgdistutilssetupscripthtml

IcanrsquotseemtoloadtheNAMEmoduleandjustgetanImportErrorMakesurethatyoumadetheNAME__init__pyfileIfyoursquoreonWindowsmakesureyoudidnrsquotaccidentallynameitNAME__init__pytxtwhichhappensbydefaultwithsomeeditors

WhydoweneedabinfolderatallThisisjustastandardplacetoputscriptsthatarerunonthecommandlinenotaplacetoputmodules

MynosetestsrunonlyshowsonetestbeingrunIsthatrightYesthatrsquoswhatmyoutputshowstoo

Exercise47AutomatedTesting

HavingtotypecommandsintoyourgameoverandovertomakesureitrsquosworkingisannoyingWouldnrsquotitbebettertowritelittlepiecesofcodethattestyourcodeThenwhenyoumakeachangeoraddanewthingtoyourprogramyoujustldquorunyourtestsrdquoandthetestsmakesurethingsarestillworkingTheseautomatedtestswonrsquotcatchallyourbugsbuttheywillcutdownonthetimeyouspendrepeatedlytypingandrunningyourcodeEveryexerciseafterthisonewillnothaveaWhatYouShouldSeesectionbutinsteadwillhaveaWhatYouShouldTestsectionYouwillbewritingautomatedtestsforallofyourcodestartingnowandthiswillhopefullymakeyouanevenbetterprogrammerIwonrsquottrytoexplainwhyyoushouldwriteautomatedtestsIwillonlysaythatyouaretryingtobeaprogrammerandprogrammersautomateboringandtedioustasksTestingapieceofsoftwareisdefinitelyboringandtedioussoyoumightaswellwritealittlebitofcodetodoitforyouThatshouldbealltheexplanationyouneedbecauseyourreasonforwritingunittestsistomakeyourbrainstrongerYouhavegonethroughthisbookwritingcodetodothingsNowyouaregoingtotakethenextleapandwritecodethatknowsaboutothercodeyouhavewrittenThisprocessofwritingatestthatrunssomecodeyouhavewrittenforcesyoutounderstandclearlywhatyouhavejustwrittenItsolidifiesinyourbrainexactlywhatitdoesandwhyitworksandgivesyouanewlevelofattentiontodetail

WritingaTestCaseWersquoregoingtotakeaverysimplepieceofcodeandwriteonesimpletestWersquoregoingtobasethislittletestonanewprojectfromyourprojectskeletonFirstmakeanex47projectfromyourprojectskeletonHerearethestepsyoushouldtakeIrsquomgoingtogivetheseinstructionsinEnglishratherthanshowyouhowtotypethemsothatyouhavetofigureitout

1Copyskeletontoex472RenameeverythingwithNAMEtoex473ChangethewordNAMEinallthefilestoex474Finallyremoveallthepycfilestomakesureyoursquoreclean

ReferbacktoExercise46ifyougetstuckandifyoucanrsquotdothiseasilythen

maybepracticeitafewtimes

WarningRememberthatyourunthecommandnoseteststorunthetestsYoucanrunthemwithpython36ex47_testspybutitwonrsquotworkaseasilyandyoursquollhavetodoitforeachtestfile

Nextcreateasimplefileex47gamepywhereyoucanputthecodetotestThiswillbeaverysillylittleclassthatwewanttotestwiththiscodeinitClickheretoviewcodeimage

gamepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name

5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)Onceyouhavethatfile

changetheunittestskeletontothisClickheretoviewcodeimage

ex47_testspy

1fromnosetoolsimport

2fromex47gameimportRoom

3

4

5deftest_room()

6gold=Room(GoldRoom

7Thisroomhasgoldinityoucangrab

Theresa

8doortothenorth)

9assert_equal(goldnameGoldRoom)

10assert_equal(goldpaths)

11

12deftest_room_paths()

13center=Room(CenterTestroominthecenter)

14north=Room(NorthTestroominthenorth)

15south=Room(SouthTestroominthesouth)

16

17centeradd_paths(northnorthsouthsouth)

18assert_equal(centergo(north)north)

19assert_equal(centergo(south)south)

20

21deftest_map()

22start=Room(StartYoucangowestanddownahole)

23west=Room(TreesTherearetreeshereyoucango

east)

24down=Room(DungeonItsdarkdownhereyoucango

up)

25

26startadd_paths(westwestdowndown)

27westadd_paths(eaststart)

28downadd_paths(upstart)

29

30assert_equal(startgo(west)west)

31assert_equal(startgo(west)go(east)start)

32assert_equal(startgo(down)go(up)start)Thisfile

importstheRoomclassyoumadeintheex47gamemodulesothatyou

candotestsonitThereisthenasetofteststhatarefunctions

startingwithtest_Insideeachtestcasetherersquosabitofcodethat

makesaroomorasetofroomsandthenmakessuretheroomswork

thewayyouexpectthemtoworkIttestsoutthebasicroom

featuresthenthepathsthentriesoutawholemap

Theimportantfunctionshereareassert_equalwhichmakessurethatvariablesyouhavesetorpathsyouhavebuiltinaRoomareactuallywhatyouthinktheyareIfyougetthewrongresultthennosetestswillprintoutanerrormessagesoyoucangofigureitout

TestingGuidelinesFollowthisloosesetofguidelineswhenmakingyourtests

1TestfilesgointestsandarenamedBLAH_testspyotherwisenosetestswonrsquotrunthemThisalsokeepsyourtestsfromclashingwithyourothercode

2Writeonetestfileforeachmoduleyoumake3Keepyourtestcases(functions)shortbutdonotworryiftheyareabitmessyTestcasesareusuallykindofmessy

4EventhoughtestcasesaremessytrytokeepthemcleanandremoveanyrepetitivecodeyoucanCreatehelperfunctionsthatgetridofduplicatecodeYouwillthankmelaterwhenyoumakeachangeandthenhaveto

codeYouwillthankmelaterwhenyoumakeachangeandthenhavetochangeyourtestsDuplicatedcodewillmakechangingyourtestsmoredifficult

5FinallydonotgettooattachedtoyourtestsSometimesthebestwaytoredesignsomethingistojustdeleteitandstartover

WhatYouShouldSeeClickheretoviewcodeimage

Exercise47Session

$nosetests

---------------------------------------------------------------------

-

Ran3testsin0008s

OK

ThatrsquoswhatyoushouldseeifeverythingisworkingrightTrycausinganerrortoseewhatthatlookslikeandthenfixit

StudyDrills1Goreadaboutnosetestsmoreandalsoreadaboutalternatives2LearnaboutPythonrsquosldquodoctestsrdquoandseeifyoulikethembetter3Makeyourroommoreadvancedandthenuseittorebuildyourgameyetagainbutthistimeunittestasyougo

CommonStudentQuestionsIgetasyntaxerrorwhenIrunnosetestsIfyougetthatthenlookatwhattheerrorsaysandfixthatlineofcodeortheonesaboveitToolslikenosetestsarerunningyourcodeandthetestcodesotheywillfindsyntaxerrorsthesameasrunningPythonwill

Icanrsquotimportex47gameMakesureyoucreatetheex47__init__pyfileRefertoExercise46againtoseehowitrsquosdoneIfthatrsquosnottheproblemthendothisonmacOSLinuxexportPYTHONPATH=AndonWindowsClickheretoviewcodeimage

$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

FinallymakesureyoursquorerunningthetestswithnosetestsnotwithjustPython

IgetUserWarningwhenIrunnosetestsYouprobablyhavetwoversionsofPythoninstalledoryouarenrsquotusingdistributeGobackandinstalldistributeorpipasIdescribeinExercise46

Exercise48AdvancedUserInput

InpastgamesyouhandledtheuserrsquosinputbysimplyexpectingsetstringsIftheusertypedldquorunrdquoandexactlyldquorunrdquothenthegameworkedIftheytypedinsimilarphraseslikeldquorunfastrdquoitwouldfailWhatweneedisadevicethatletsuserstypephrasesinvariouswaysandthenconvertthatintosomethingthecomputerunderstandsForexamplewersquodliketohaveallofthesephrasesworkthesamebullopendoorbullopenthedoorbullgoTHROUGHthedoorbullpunchbearbullPunchTheBearintheFACEItshouldbealrightforausertowritesomethingalotlikeEnglishforyourgameandhaveyourgamefigureoutwhatitmeansTodothiswersquoregoingtowriteamodulethatdoesjustthatThismodulewillhaveafewclassesthatworktogethertohandleuserinputandconvertitintosomethingyourgamecanworkwithreliablyAsimplifiedversionoftheEnglishlanguagecouldincludethefollowingelementsbullWordsseparatedbyspacesbullSentencescomposedofthewordsbullGrammarthatstructuresthesentencesintomeaningThatmeansthebestplacetostartisfiguringouthowtogetwordsfromtheuserandwhatkindsofwordsthoseare

OurGameLexiconInourgamewehavetocreatealistofallowablewordscalledaldquolexiconrdquo

bullDirectionwordsnorthsoutheastwestdownupleftrightbackbullVerbsgostopkilleatbullStopwordstheinoffromatitbullNounsdoorbearprincesscabinetbullNumbersanystringof0through9charactersWhenwegettonounswehaveaslightproblemsinceeachroomcouldhaveadifferentsetofnounsbutletrsquosjustpickthissmallsettoworkwithfornowandimproveitlater

BreakingUpaSentenceOncewehaveourlexiconweneedawaytobreakupsentencessothatwecanfigureoutwhattheyareInourcasewersquovedefinedasentenceasldquowordsseparatedbyspacesrdquosowereallyjustneedtodothis

stuff=input(gt)

words=stuffsplit()Thatrsquosallwersquollworryaboutfornowbutthis

willworkreallywellforquiteawhile

LexiconTuples

LexiconTuplesOnceweknowhowtobreakupasentenceintowordswejusthavetogothroughthelistofwordsandfigureoutwhatldquotyperdquotheyareTodothatwersquoregoingtouseahandylittlePythonstructurecalledaldquotuplerdquoAtupleisnothingmorethanalistthatyoucanrsquotmodifyItrsquoscreatedbyputtingdatainsideasetofparentheseswithacommalikealistClickheretoviewcodeimage

first_word=(verbgo)

second_word=(directionnorth)

third_word=(directionwest)

sentence=[first_wordsecond_wordthird_word]

Thiscreatesapair(TYPEWORD)thatletsyoulookatthewordanddothingswithitThisisjustanexamplebutthatrsquosbasicallytheendresultYouwanttotakerawinputfromtheusercarveitintowordswithsplitanalyzethosewordstoidentifytheirtypesandfinallymakeasentenceoutofthem

ScanningInputNowyouarereadytowriteyourscannerThisscannerwilltakeastringofrawinputfromauserandreturnasentencethatrsquoscomposedofalistoftupleswiththe(TOKENWORD)pairingsIfawordisnrsquotpartofthelexiconthenitshouldstillreturntheWORDbutsettheTOKENtoanerrortokenTheseerrortokenswilltelluserstheymessedupHerersquoswhereitgetsfunIrsquomnotgoingtotellyouhowtodothisInsteadIrsquomgoingtowritealdquounittestrdquoandyouaregoingtowritethescannersothattheunittestworks

ExceptionsandNumbersThereisonetinythingIwillhelpyouwithfirstandthatrsquosconvertingnumbersInordertodothisthoughwersquoregoingtocheatanduseexceptionsAnexceptionisanerrorthatyougetfromsomefunctionyoumayhaverunWhathappensisyourfunctionldquoraisesrdquoanexceptionwhenitencountersanerrorthenyouhavetohandlethatexceptionForexampleifyoutypethisintoPythonyougetanexceptionClickheretoviewcodeimage

Exercise48PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtint(hell)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

ValueErrorinvalidliteralforint()withbase10hell

ThatValueErrorisanexceptionthattheint()functionthrewbecausewhatyouhandedint()isnotanumberTheint())functioncouldhavereturnedavaluetotellyouithadanerrorbutsinceitonlyreturnsintegersitrsquodhaveahardtimedoingthatItcanrsquotreturn-1sincethatrsquosanumberInsteadoftryingtofigureoutwhattoreturnwhentherersquosanerrortheint()functionraisestheValueErrorexceptionandyoudealwithitYoudealwithanexceptionbyusingthetryandexceptkeywordsex48_convertpy

1defconvert_number(s)

2try

3returnint(s)

4exceptValueError

5returnNoneYouputthecodeyouwanttoldquotryrdquoinside

thetryblockandthenyouputthecodetorunfortheerrorinside

theexceptInthiscasewewanttoldquotryrdquotocallint()onsomething

thatmightbeanumberIfthathasanerrorthenweldquocatchrdquoitand

returnNone

InyourscannerthatyouwriteyoushouldusethisfunctiontotestwhethersomethingisanumberYoushouldalsodoitasthelastthingyoucheckforbeforedeclaringthatwordanerrorword

ATestFirstChallengeTestfirstisaprogrammingtacticwhereyouwriteanautomatedtestthatpretendsthecodeworksthenyouwritethecodetomakethetestactuallyworkThismethodworkswhenyoucanrsquotvisualizehowthecodeisimplementedbutyoucanimaginehowyouhavetoworkwithitForexampleifyouknowhowyouneedtouseanewclassinanothermodulebutyoudonrsquotquiteknowhowtoimplementthatclassyetthenwritethetestfirstYouaregoingtotakeatestIgiveyouanduseittowritethecodethatmakesitworkTodothisexercisefollowthisprocedure1CreateonesmallpartofthetestIgiveyou

2Makesureitrunsandfailssoyouknowthatthetestisactuallyconfirmingafeatureworks

3Gotoyoursourcefilelexiconpyandwritethecodethatmakesthistestpass

4RepeatuntilyouhaveimplementedeverythinginthetestWhenyougettostep3itrsquosalsogoodtocombineourothermethodofwritingcode1Maketheldquoskeletonrdquofunctionorclassthatyouneed

2Writecommentsinsidedescribinghowthatfunctionworks3Writethecodethatdoeswhatthecommentsdescribe4Removeanycommentsthatjustrepeatthecode

ThismethodofwritingcodeiscalledldquopsuedocoderdquoandworkswellifyoudonrsquotknowhowtoimplementsomethingbutyoucandescribeitinyourownwordsCombiningtheldquotestfirstrdquowiththeldquopsuedocoderdquotacticswehavethissimpleprocessforprogramming1Writeabitoftestthatfails

2Writetheskeletonfunctionmoduleclassthetestneeds3Filltheskeletonwithcommentsinyourownwordsexplaininghowitworks

4Replacethecommentswithcodeuntilthetestpasses5Repeat

InthisexerciseyouwillpracticethismethodofworkingbymakingatestIgiveyourunagainstthelexiconpymodule

WhatYouShouldTestHereisthetestcasetestslexicon_testspythatyoushouldusebutdonrsquottypethisinyetClickheretoviewcodeimage

lexicon_testspy

1fromnosetoolsimport

2fromex48importlexicon

3

4

5deftest_directions()

6assert_equal(lexiconscan(north)[(direction

north)])

7result=lexiconscan(northsoutheast)

8assert_equal(result[(directionnorth)

9(directionsouth)

10(directioneast)])

11

12deftest_verbs()

13assert_equal(lexiconscan(go)[(verbgo)])

14result=lexiconscan(gokilleat)

15assert_equal(result[(verbgo)

16(verbkill)

17(verbeat)])

18

19

20deftest_stops()

21assert_equal(lexiconscan(the)[(stopthe)])

22result=lexiconscan(theinof)

23assert_equal(result[(stopthe)

24(stopin)

25(stopof)])

26

27

28deftest_nouns()

29assert_equal(lexiconscan(bear)[(nounbear)])

30result=lexiconscan(bearprincess)

31assert_equal(result[(nounbear)

32(nounprincess)])

33

34deftest_numbers()

35assert_equal(lexiconscan(1234)[(number1234)])

36result=lexiconscan(391234)

37assert_equal(result[(number3)

38(number91234)])

39

40

41deftest_errors()

42assert_equal(lexiconscan(ASDFADFASDF)

43[(errorASDFADFASDF)])

44result=lexiconscan(bearIASprincess)

45assert_equal(result[(nounbear)

46(errorIAS)

47(nounprincess)])Youwillwant

tocreateanewprojectusingtheprojectskeletonjustlikeyoudid

inExercise47Thenyoursquollneedtocreatethistestcaseandthe

lexiconpyfileitwilluseLookatthetopofthetestcasetosee

howitrsquosbeingimportedtofigureoutwhereitgoes

NextfollowtheprocedureIgaveyouandwritealittlebitofthetestcaseatatimeForexampleherersquoshowIrsquoddoit1WritetheimportatthetopGetthattowork

2Createanemptyversionofthefirsttestcasetest_directionsMakesurethatruns

3Writethefirstlineofthetest_directionstestcaseMakeitfail4Gotothelexiconpyfileandcreateanemptyscanfunction5Runthetestandmakesurescanisatleastrunningeventhoughitfails6Fillinpsuedocodecommentsforhowscanshouldworktomaketest_directionspass

7Writethecodethatmatchesthecommentsuntiltest_directionspasses

8Gobacktotest_directionsandwritetherestofthelines9Gobacktoscaninlexiconpyandworkonittomakethisnewtestcodepass

10Onceyoursquovedonethatyouhaveyourfirstpassingtestandyoumoveontothenexttest

AslongasyoukeepfollowingthisprocedureonelittlechunkatatimeyoucansuccessfullyturnalargeproblemintosmallersolvableproblemsItrsquoslikeclimbingamountainbyturningitintoabunchoflittlehills

StudyDrills1Improvetheunittesttomakesureyoutestmoreofthelexicon2Addtothelexiconandthenupdatetheunittest3MakesureyourscannerhandlesuserinputinanycapitalizationandcaseUpdatethetesttomakesurethisactuallyworks

4Findanotherwaytoconvertthenumber5Mysolutionwas37lineslongIsyourslongerShorter

CommonStudentQuestionsWhydoIkeepgettingImportErrorsImporterrorsareusuallycausedbyfourthings1Youdidnrsquotmakean__init__pyinadirectorythathasmodulesinit2Youareinthewrongdirectory3Youareimportingthewrongmodulebecauseyouspelleditwrong4YourPYTHONPATHisnrsquotsettosoyoucanrsquotloadmodulesfromyourcurrentdirectory

Whatrsquosthedifferencebetweentry-exceptandif-elseThe

try-exceptconstructisonlyusedforhandlingexceptionsthatmodulescanthrowItshouldneverbeusedasanalternativetoif-else

IsthereawaytokeepthegamerunningwhiletheuseriswaitingtotypeIrsquomassumingyouwanttohaveamonsterattackusersiftheydonrsquotreactquicklyenoughItispossiblebutitinvolvesmodulesandtechniquesthatareoutsideofthisbookrsquosdomain

Exercise49MakingSentences

WhatweshouldbeabletogetfromourlittlegamelexiconscannerisalistthatlookslikethisClickheretoviewcodeimage

Exercise49PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48importlexicon

gtgtgtlexiconscan(gonorth)

[(verbgo)(directionnorth)]

gtgtgtlexiconscan(killtheprincess)

[(verbkill)(stopthe)(nounprincess)]

gtgtgtlexiconscan(eatthebear)

[(verbeat)(stopthe)(nounbear)]

Thiswillalsoworkonlongersentencessuchaslexiconscan(openthedoorandsmackthebearinthenose)NowletusturnthisintosomethingthegamecanworkwithwhichwouldbesomekindofSentenceclassIfyouremembergradeschoolasentencecanbeasimplestructurelikeSubjectVerbObjectObviouslyitgetsmorecomplexthanthatandyouprobablydidmanydaysofannoyingsentencediagramsforEnglishclassWhatwewantistoturntheprecedinglistsoftuplesintoaniceSentenceobjectthathassubjectverbandobject

MatchandPeekTodothisweneedfivetools

1AwaytoloopthroughthelistofscannedwordsThatrsquoseasy2AwaytoldquomatchrdquodifferenttypesoftuplesthatweexpectinourSubjectVerbObjectsetup

3Awaytoldquopeekrdquoatapotentialtuplesowecanmakesomedecisions4Awaytoldquoskiprdquothingswedonotcareaboutlikestopwords5ASentenceobjecttoputtheresultsin

Wewillbeputtingthesefunctionsinamodulenamedex48parserinafilenamedex48parserpyinordertotestitWeusethepeekfunctiontosay

ldquolookatthenextelementinourtuplelistandthenmatchtotakeoneoffandworkwithitrdquo

TheSentenceGrammarBeforeyoucanwritethecodeyouneedtounderstandhowbasicEnglishsentencegrammarworksInourparserwewanttoproduceaSentenceobjectthathasthreeattributes

SentencesubjectThisisthesubjectofanysentencebutcoulddefaulttoldquoplayerrdquomostofthetimesinceasentenceofldquorunnorthrdquoisimplyingldquoplayerrunnorthrdquoThiswillbeanoun

SentenceverbThisistheactionofthesentenceInldquorunnorthrdquoitwouldbeldquorunrdquoThiswillbeaverb

SentenceobjectThisisanothernounthatreferstowhattheverbisdoneonInourgameweseparateoutdirectionswhichwouldalsobeobjectsInldquorunnorthrdquothewordldquonorthrdquowouldbetheobjectInldquohitbearrdquothewordldquobearrdquowouldbetheobject

OurparserthenhastousethefunctionswedescribedandgivenascannedsentenceconvertitintoanListofSentenceobjectstomatchtheinput

AWordonExceptionsYoubrieflylearnedaboutexceptionsbutnothowtoraisethemThiscodedemonstrateshowtodothatwiththeParserErroratthetopNoticethatitusesclassestogiveitthetypeofExceptionAlsonoticetheuseoftheraisekeywordtoraisetheexceptionInyourtestsyouwillwanttoworkwiththeseexceptionswhichIrsquollshowyouhowtodo

TheParserCodeIfyouwantanextrachallengestoprightnowandtrytowritethisbasedonjustmydescriptionIfyougetstuckyoucancomebackandseehowIdiditbuttryingtoimplementtheparseryourselfisgoodpracticeIwillnowwalkthroughthecodesoyoucanenteritintoyourex48parserpyWestarttheparserwiththeexceptionweneedforaparsingerrorClickheretoviewcodeimage

parserpy

1classParserError(Exception)

2pass

ThisishowyoumakeyourownParserErrorexceptionclassyoucanthrowNextweneedtheSentenceobjectwersquollcreateClickheretoviewcodeimage

parserpy

1classSentence(object)

2

3def__init__(selfsubjectverbobj)

4rememberwetake(nounprincess)tuplesand

convertthem

5selfsubject=subject[1]

6selfverb=verb[1]

7selfobject=obj[1]

TherersquosnothingspecialaboutthiscodesofarYoursquorejustmakingsimpleclassesInourdescriptionoftheproblemweneedafunctionthatcanpeekatalistofwordsandreturnwhattypeofworditisClickheretoviewcodeimage

parserpy

1defpeek(word_list)

2ifword_list

3word=word_list[0]

4returnword[0]

5else

6returnNoneWeneedthisfunctionbecausewersquollhaveto

makedecisionsaboutwhatkindofsentencewersquoredealingwithbased

onwhatthenextwordisThenwecancallanotherfunctionto

consumethatwordandcarryon

ToconsumeawordweusethematchfunctionwhichconfirmsthattheexpectedwordistherighttypetakesitoffthelistandreturnsthewordClickheretoviewcodeimage

parserpy

1defmatch(word_listexpecting)

2ifword_list

3word=word_listpop(0)

4

5ifword[0]==expecting

6returnword

7else

8returnNone

9else

10returnNoneAgainthisisfairlysimplebutmakesure

youunderstandthiscodeAlsomakesureyouunderstandwhyIrsquomdoing

itthiswayIneedtopeekatwordsinthelisttodecidewhatkind

ofsentenceIrsquomdealingwithandthenIneedtomatchthosewordsto

createmySentence

ThelastthingIneedisawaytoskipwordsthatarenrsquotusefultotheSentenceThesearethewordslabeledldquostopwordsrdquo(typestop)thatarewordslikeldquotherdquoldquoandrdquoandldquoardquoClickheretoviewcodeimage

parserpy

1defskip(word_listword_type)

2whilepeek(word_list)==word_type

3match(word_listword_type)Rememberthatskipdoesnrsquot

skiponeworditskipsasmanywordsofthattypeasitfindsThis

makesitsoifsomeonetypesldquoscreamatthebearrdquoyougetldquoscreamrdquo

andldquobearrdquo

ThatrsquosourbasicsetofparsingfunctionsandwiththatwecanactuallyparsejustaboutanytextwewantOurparserisverysimplethoughsotheremainingfunctionsareshortFirstwecanhandleparsingaverbClickheretoviewcodeimage

parserpy

1defparse_verb(word_list)

2skip(word_liststop)

3

4ifpeek(word_list)==verb

5returnmatch(word_listverb)

6else

7raiseParserError(Expectedaverbnext)Weskipany

stopwordsthenpeekaheadtomakesurethenextwordisaldquoverbrdquo

typeIfitrsquosnotthenraisetheParserErrortosaywhyIfitisa

ldquoverbrdquothenmatchitwhichtakesitoffthelistAsimilar

functionhandlessentenceobjectsClickheretoviewcodeimage

parserpy

1defparse_object(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==direction

8returnmatch(word_listdirection)

9else

10raiseParserError(Expectedanounordirectionnext)

Againskipthestopwordspeekaheadanddecideifthesentenceis

correctbasedonwhatrsquosthereIntheparse_objectfunctionthough

weneedtohandlebothldquonounrdquoandldquodirectionrdquowordsaspossible

objectsSubjectsarethensimilaragainbutsincewewanttohandle

theimpliedldquoplayerrdquonounwehavetousepeekClickheretoview

codeimage

parserpy

1defparse_subject(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==verb

8return(nounplayer)

9else

10raiseParserError(Expectedaverbnext)Withthat

alloutofthewayandreadyourfinalparse_sentencefunctionis

verysimpleClickheretoviewcodeimage

parserpy

1defparse_sentence(word_list)

2subj=parse_subject(word_list)

3verb=parse_verb(word_list)

4obj=parse_object(word_list)

5

6returnSentence(subjverbobj)

PlayingwiththeParserToseehowthisworksyoucanplaywithitlikethis

ToseehowthisworksyoucanplaywithitlikethisClickheretoviewcodeimage

Exercise49aPythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48parserimport

gtgtgtx=parse_sentence([(verbrun)(directionnorth)])

gtgtgtxsubject

player

gtgtgtxverb

run

gtgtgtxobject

north

gtgtgtx=parse_sentence([(nounbear)(verbeat)(stop

the)

(nounhoney)])

gtgtgtxsubject

bear

gtgtgtxverb

eat

gtgtgtxobject

honey

TrytomapsentencestothecorrectpairingsinasentenceForexamplehowwouldyousayldquothebearrunsouthrdquo

WhatYouShouldTestForExercise49writeacompletetestthatconfirmseverythinginthiscodeisworkingPutthetestintestsparser_testspysimilartothetestfilefromthelastexerciseThatincludesmakingexceptionshappenbygivingtheparserbadsentencesCheckforanexceptionbyusingthefunctionassert_raisesfromthenosedocumentationLearnhowtousethissoyoucanwriteatestthatisexpectedtofailwhichisveryimportantintestingLearnaboutthisfunction(andothers)byreadingthenosedocumentationWhenyouaredoneyoushouldknowhowthisbitofcodeworksandhowtowriteatestforotherpeoplersquoscodeeveniftheydonotwantyoutoTrustmeitrsquosaveryhandyskilltohave

StudyDrills

StudyDrills1Changetheparse_methodsandtrytoputthemintoaclassratherthanusethemjustasmethodsWhichdesigndoyoulikebetter

2Maketheparsermoreerror-resistantsothatyoucanavoidannoyingyourusersiftheytypewordsyourlexicondoesnrsquotunderstand

3Improvethegrammarbyhandlingmorethingslikenumbers4ThinkabouthowyoumightusethisSentenceclassinyourgametodomorefunthingswithauserrsquosinput

CommonStudentQuestionsIcanrsquotseemtomakeassert_raisesworkrightMakesureyouarewritingassert_raises(exceptioncallableparameters)andnotwritingassert_raises(exceptioncallable(parameters))Noticehowthesecondformiscallingthefunctionthenpassingtheresulttoassert_raiseswhichiswrongYouhavetopassthefunctiontocallanditsargumentstoassert_raises

Exercise50YourFirstWebsite

ThesefinalthreeexerciseswillbeveryhardandyoushouldtakeyourtimewiththemInthisfirstoneyoursquollbuildasimplewebversionofoneofyourgamesBeforeyouattemptthisexerciseyoumusthavecompletedExercise46successfullyandhaveaworkingpipinstalledsuchthatyoucaninstallpackagesandknowhowtomakeaskeletonprojectdirectoryIfyoudonrsquotrememberhowtodothisgobacktoExercise46anddoitalloveragain

InstallingflaskBeforecreatingyourfirstwebapplicationyoursquollfirstneedtoinstalltheldquowebframeworkrdquocalledflaskThetermldquoframeworkrdquogenerallymeansldquosomepackagethatmakesiteasierformetodosomethingrdquoIntheworldofwebapplicationspeoplecreateldquowebframeworksrdquotocompensateforthedifficultproblemstheyrsquoveencounteredwhenmakingtheirownsitesTheysharethesecommonsolutionsintheformofapackageyoucandownloadtobootstrapyourownprojectsInourcasewersquollbeusingtheflaskframeworkbuttherearemanymanymanyothersyoucanchoosefromFornowlearnflaskthenbranchouttoanotheronewhenyoursquoreready(orjustkeepusingflasksinceitrsquosgoodenough)UsingpipinstallflaskClickheretoviewcodeimage

$sudopipinstallflask

[sudo]passwordforzedshaw

Downloadingunpackingflask

Runningsetuppyegg_infoforpackageflask

Installingcollectedpackagesflask

Runningsetuppyinstallforflask

Successfullyinstalledflask

Cleaningup

ThiswillworkonLinuxandmacOScomputersbutonWindowsjustdropthesudopartofthepipinstallcommandanditshouldworkIfnotgobacktoExercise46andmakesureyoucandoitreliably

MakeaSimpleldquoHelloWorldrdquoProject

NowyoursquoregoingtomakeaninitialverysimpleldquoHelloWorldrdquowebapplicationandprojectdirectoryusingflaskFirstmakeyourprojectdirectoryClickheretoviewcodeimage

$cdprojects

$mkdirgothonweb

$cdgothonweb

$mkdirbingothonwebtestsdocstemplates

$touchgothonweb__init__py

$touchtests__init__py

YoursquollbetakingthegamefromExercise43andmakingitintoawebapplicationsothatrsquoswhyyoursquorecallingitgothonwebBeforeyoudothatweneedtocreatethemostbasicflaskapplicationpossiblePutthefollowingcodeintoapppyClickheretoviewcodeimage

ex50py

1fromflaskimportFlask

2app=Flask(__name__)

3

4approute()

5defhello_world()

6returnHelloWorld

7

8if__name__==__main__

9apprun()ThenruntheapplicationlikethisClickhereto

viewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)Finally

useyourwebbrowserandgotohttplocalhost5000andyoushould

seetwothingsFirstinyourbrowseryoursquollseeHelloworld

SecondyoursquollseeyourTerminalwithnewoutputlikethisClick

heretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

127001ndashndash[22Feb2017142850]GETHTTP11200ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

ThosearelogmessagesthatflaskprintsoutsoyoucanseethattheserverisworkingandwhatthebrowserisdoingbehindthescenesThelogmessageshelpyoudebugandfigureoutwhenyouhaveproblemsForexampleitrsquossayingthatyourbrowsertriedtogetfaviconicobutthatfiledidnrsquotexistsoit

returnedthe404NotFoundstatuscodeIhavenrsquotexplainedthewayanyofthiswebstuffworksyetbecauseIwanttogetyousetupandreadytorollsothatIcanexplainitbetterinthenexttwoexercisesToaccomplishthisIrsquollhaveyoubreakyourflaskapplicationinvariouswaysandthenrestructureitsothatyouknowhowitrsquossetup

WhatrsquosGoingOnHerersquoswhatrsquoshappeningwhenyourbrowserhitsyourapplication

1YourbrowsermakesanetworkconnectiontoyourowncomputerwhichiscalledlocalhostandisastandardwayofsayingldquowhatevermyowncomputeriscalledonthenetworkrdquoItalsousesport5000

2OnceitconnectsitmakesanHTTPrequesttotheapppyapplicationandasksfortheURLwhichiscommonlythefirstURLonanywebsite

3InsideapppyyoursquovegotalistofURLsandwhatfunctionstheymatchTheonlyonewehaveistheindexmappingThismeansthatwheneversomeonegoestowithabrowserflaskwillfindthedefindexandrunittohandletherequest

4NowthatflaskhasfounddefindexitcallsittoactuallyhandletherequestThisfunctionrunsandsimplyreturnsastringforwhatflaskshouldsendtothebrowser

5Finallyflaskhashandledtherequestandsendsthisresponsetothebrowserwhichiswhatyouareseeing

MakesureyoureallyunderstandthisDrawupadiagramofhowthisinformationflowsfromyourbrowsertoflaskthentodefindexandbacktoyourbrowser

FixingErrorsFirstdeleteline8whereyouassignthegreetingvariablethenhitrefreshinyourbrowserThenuseCTRL-CtokillflaskandstartitagainOnceitrsquosrunningagainrefreshyourbrowserandyoushouldseeanldquoInternalServerErrorrdquoBackinyourTerminalyoursquollseethis([VENV]isthepathtoyourvenvsdirectory)Clickheretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

[2017ndash02ndash22143554256]ERRORinappExceptionon[GET]

Traceback(mostrecentcalllast)

File[VENV]site-packagesflaskapppy

line1982inwsgi_app

response=selffull_dispatch_request()

File[VENV]site-packagesflaskapppy

line1614infull_dispatch_request

rv=selfhandle_user_exception(e)

File[VENV]site-packagesflaskapppy

line1517inhandle_user_exception

reraise(exc_typeexc_valuetb)

File[VENV]site-packagesflask_compatpy

line33inreraise

raisevalue

File[VENV]site-packagesflaskapppy

line1612infull_dispatch_request

rv=selfdispatch_request()

File[VENV]site-packagesflaskapppy

line1598indispatch_request

returnselfview_functions[ruleendpoint](reqview_args)

Fileapppyline8inindex

returnrender_template(indexhtmlgreeting=greeting)

NameErrornamegreetingisnotdefined

127001ndashndash[22Feb2017143554]GETHTTP11500ndash

ThisworkswellenoughbutyoucanalsorunflaskinldquodebuggermoderdquoThiswillgiveyouabettererrorpageandmoreusefulinformationTheproblemwithdebuggermodeisitrsquosnotsafetorunontheinternetsoyouhavetoexplicitlyturnitonlikethisClickheretoviewcodeimage

(lpthw)$exportFLASK_DEBUG=1

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

Restartingwithstat

Debuggerisactive

Debuggerpincode222ndash752ndash342

Afterthisyouhitrefreshinyourbrowserandyougetamuchmoredetailedpagewithinformationyoucanusetodebugtheapplicationandaliveconsoletoworkwithtofindoutmore

WarningItrsquostheflasklivedebuggingconsoleandtheimprovedoutputthatmakesdebugmodesodangerousontheinternetWiththisinformationanattackercancompletelycontrolyourmachineremotelyIfyoueverdoplaceyourwebapplicationontheinternetdonotactivatedebuggermodeInfactIwouldavoid

makingFLASK_DEBUGeasytoactivateItrsquostemptingtosimplyhackthisstartupsothatyousaveastepduringdevelopmentbutthenthathackwillgetontoyourwebserveranditrsquollturnintoarealhacknotjustsomethinglazyyoudidonenightwhenyouweretired

CreateBasicTemplatesYoucanbreakyourflaskapplicationbutdidyounoticethatldquoHelloWorldrdquoisnrsquotaverygoodHTMLpageThisisawebapplicationandassuchitneedsaproperHTMLresponseTodothatyouwillcreateasimpletemplatethatsaysldquoHelloWorldrdquoinabiggreenfontThefirststepistocreateatemplatesindexhtmlfilethatlookslikethisClickheretoviewcodeimage

indexhtml

lthtmlgt

ltheadgt

lttitlegtGothonsOfPlanetPercal25lttitlegt

ltheadgt

ltbodygt

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

ltbodygt

lthtmlgtIfyouknowwhatHTMListhenthisshouldlookfairly

familiarIfnotresearchHTMLandtrywritingafewwebpagesby

handsoyouknowhowitworksThisHTMLfilehoweverisa

templatewhichmeansthatflaskwillfillinldquoholesrdquointhetext

dependingonvariablesyoupassintothetemplateEveryplaceyou

see$greetingwillbeavariableyoursquollpasstothetemplatethat

altersitscontents

TomakeyourapppydothisyouneedtoaddsomecodetotellflaskwheretoloadthetemplateandtorenderitTakethatfileandchangeitlikethisClickheretoviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3

4app=Flask(__name__)

5

6approute()

7defindex()

8greeting=HelloWorld

9returnrender_template(indexhtmlgreeting=greeting)

10

11if__name__==__main__

12apprun()Paycloseattentiontothenewrendervariable

andhowIchangedthelastlineofindexGETsoitreturns

renderindex()passinginyourgreetingvariable

OnceyouhavethatinplacereloadthewebpageinyourbrowserandyoushouldseeadifferentmessageingreenYoushouldalsobeabletodoaViewSourceonthepageinyourbrowsertoseethatitisvalidHTMLThismayhaveflownbyyouveryfastsoletmeexplainhowatemplateworks1Inyourapppyyoursquoveimportedanewfunctionnamedrender_templateatthetop

2Thisrender_templateknowshowtoloadhtmlfilesoutofthetemplatesdirectorybecausethatisthedefaultmagicsettingforaflaskapplication

3Laterinyourcodewhenthebrowserhitsthedefindexinsteadofjustreturningthestringgreetingyoucallrender_templateandpassthegreetingtoitasavariable

4Thisrender_templatemethodthenloadsthetemplatesindexhtmlfile(eventhoughyoudidnrsquotexplicitlysaytemplates)andprocessesit

5InthistemplatesindexhtmlfileyouhavewhatlookslikenormalHTMLbutthentherersquosldquocoderdquoplacedbetweentwokindsofmarkersOneiswhichmarkspiecesofldquoexecutablecoderdquo(if-statementsfor-loopsetc)TheotheriswhichmarksvariablestobeconvertedintotextandplacedintotheHTMLoutputTheexecutablecodedoesnrsquotshowupintheHTMLTolearnmoreaboutthistemplatelanguagereadtheJinja2documentation

TogetdeeperintothischangethegreetingvariableandtheHTMLtoseewhateffectithasAlsocreateanothertemplatenamedtemplatesfoohtmlandrenderthatlikebefore

StudyDrills1Readthedocumentationathttpflaskpocooorgdocs012whichisthesameastheflaskproject

2Experimentwitheverythingyoucanfindthereincludingtheirexamplecode

3ReadaboutHTML5andCSS3andmakesomeotherhtmlandcssfilesforpractice

4IfyouhaveafriendwhoknowsDjangoandiswillingtohelpyouthenconsiderdoingExercises5051and52inDjangoinsteadtoseewhatthatrsquoslike

CommonStudentQuestionsIcanrsquotseemtoconnecttohttplocalhost5000Tryhttp1270015000instead

WhatisthedifferencebetweeflaskandwebpyNodifferenceIsimplyldquolockedrdquowebpyataparticularversionsothatitwouldbeconsistentforstudentsthennameditflaskLaterversionsofwebpymightbedifferentfromthisversion

Icanrsquotfindindexhtml(orjustaboutanything)YouprobablyaredoingcdbinfirstandthentryingtoworkwiththeprojectDonotdothisAllofthecommandsandinstructionsassumeyouareonedirectoryabovebinsoifyoucanrsquottypepython36apppythenyouareinthewrongdirectory

Whydoweassigngreeting=greetingwhenwecallthetemplateYouarenotassigningtogreetingYouaresettinganamedparametertogivetothetemplateItrsquossortofanassignmentbutitonlyaffectsthecalltothetemplatefunction

Icanrsquotuseport5000onmycomputerYouprobablyhaveananti-virusprograminstalledthatisusingthatportTryadifferentport

AfterinstallingflaskIgetImportErrorNomodulenamedwebYoumostlikelyhavemultipleversionsofpythoninstalledandareusingthewrongoneoryoudidnrsquotdotheinstall

correctlybecauseofanoldversionofpipTryuninstallingflaskandreinstallingitIfthatdoesnrsquotworkmaketriplesureyoursquoreusingtherightversionofpython

Exercise51GettingInputfromaBrowser

WhileitrsquosexcitingtoseethebrowserdisplayldquoHelloWorldrdquoitrsquosevenmoreexcitingtolettheusersubmittexttoyourapplicationfromaformInthisexercisewersquollimproveourstarterwebapplicationbyusingformsandstoringinformationaboutusersintotheirldquosessionsrdquo

HowtheWebWorksTimeforsomeboringstuffYouneedtounderstandabitmoreabouthowthewebworksbeforeyoucanmakeaformThisdescriptionisnrsquotcompletebutitrsquosaccurateandwillhelpyoufigureoutwhatmightbegoingwrongwithyourapplicationAlsocreatingformswillbeeasierifyouknowwhattheydoIrsquollstartwithasimplediagramthatshowsyouthedifferentpartsofawebrequestandhowtheinformationflows

IrsquovelabeledthelineswithletterssoIcanwalkyouthrougharegularrequestprocess1Youtypeintheurlhttptestcomintoyourbrowseranditsendstherequestonline(A)toyourcomputerrsquosnetworkinterface

2Yourrequestgoesoutovertheinternetonline(B)andthentotheremotecomputeronline(C)wheremyserveracceptstherequest

3Oncemycomputeracceptsitmywebapplicationgetsitonline(D)andmyPythoncoderunstheindexGEThandler

4TheresponsecomesoutofmyPythonserverwhenIreturnitandit

goesbacktoyourbrowseroverline(D)again5Theserverrunningthissitetakestheresponseoffline(D)thensendsitbackovertheinternetonline(C)

6Theresponsefromtheserverthencomesofftheinternetonline(B)andyourcomputerrsquosnetworkinterfacehandsittoyourbrowseronline(A)

7FinallyyourbrowserthendisplaystheresponseInthisdescriptionthereareafewtermsyoushouldknowsothatyouhaveacommonvocabularytoworkwithwhentalkingaboutyourwebapplicationBrowserThesoftwarethatyoursquoreprobablyusingeverydayMostpeopledonrsquotknowwhatabrowserreallydoesTheyjustcallbrowsersldquotheinternetrdquoItsjobistotakeaddresses(likehttptestcom)youtypeintotheURLbarthenusethatinformationtomakerequeststotheserveratthataddress

AddressThisisnormallyaURL(UniformResourceLocator)likehttptestcomandindicateswhereabrowsershouldgoThefirstparthttpindicatestheprotocolyouwanttouseinthiscaseldquoHyper-TextTransportProtocolrdquoYoucanalsotryftpibiblioorgtoseehowldquoFileTransportProtocolrdquoworksThehttptestcompartistheldquohostnamerdquoahumanreadableaddressyoucanrememberandwhichmapstoanumbercalledanIPaddresssimilartoatelephonenumberforacomputerontheinternetFinallyURLscanhaveatrailingpathlikethebookpartofhttptestcombookwhichindicatesafileorsomeresourceontheservertoretrievewitharequestTherearemanyotherpartsbutthosearethemainones

ConnectionOnceabrowserknowswhatprotocolyouwanttouse(http)whatserveryouwanttotalkto(httptestcom)andwhatresourceonthatservertogetitmustmakeaconnectionThebrowsersimplyasksyouroperatingsystem(OS)toopenaldquoportrdquotothecomputerusuallyport80WhenitworkstheOShandsbacktoyourprogramsomethingthatworkslikeafilebutisactuallysendingandreceivingbytesoverthenetworkwiresbetweenyourcomputerandtheothercomputerathttptestcomThisisalsothesamethingthathappenswithhttplocalhost8080butinthiscaseyoursquoretellingthebrowsertoconnecttoyourowncomputer(localhost)anduseport8080ratherthanthedefaultof80Youcouldalsodohttptestcom80andgetthesameresultexceptyoursquoreexplicitlysayingtouseport80insteadoflettingitbethatbydefault

RequestYourbrowserisconnectedusingtheaddressyougaveNowitneedstoaskfortheresourceitwants(oryouwant)ontheremoteserverIfyougavebookattheendoftheURLthenyouwantthefile(resource)atbookandmostserverswillusetherealfilebookindexhtmlbutpretenditdoesnrsquotexistWhatthebrowserdoestogetthisresourceissendarequesttotheserverIwonrsquotgetintoexactlyhowitdoesthisbutjustunderstandthatithastosendsomethingtoquerytheserverfortherequestTheinterestingthingisthattheseldquoresourcesrdquodonrsquothavetobefilesForinstancewhenthebrowserinyourapplicationasksforsomethingtheserverisreturningsomethingyourPythoncodegenerated

ServerTheserveristhecomputerattheendofabrowserrsquosconnectionthatknowshowtoansweryourbrowserrsquosrequestsforfilesresourcesMostwebserversjustsendfilesandthatrsquosactuallythemajorityoftrafficButyoursquoreactuallybuildingaserverinPythonthatknowshowtotakerequestsforresourcesandthenreturnstringsthatyoucraftusingPythonWhenyoudothiscraftingyouarepretendingtobeafiletothebrowserbutreallyitrsquosjustcodeAsyoucanseefromExercise50italsodoesnrsquottakemuchcodetocreatearesponse

ResponseThisistheHTML(CSSJavaScriptorimages)yourserverwantstosendbacktothebrowserastheanswertothebrowserrsquosrequestInthecaseoffilesitjustreadsthemoffthediskandsendsthemtothebrowserbutitwrapsthecontentsofthediskinaspecialldquoheaderrdquosothebrowserknowswhatitrsquosgettingInthecaseofyourapplicationyoursquorestillsendingthesamethingincludingtheheaderbutyougeneratethatdataontheflywithyourPythoncode

ThatisthefastestcrashcourseinhowawebbrowseraccessesinformationonserversontheinternetItshouldworkwellenoughforyoutounderstandthisexercisebutifnotreadaboutitasmuchasyoucanuntilyougetitAreallygoodwaytodothatistotakethediagramandbreakdifferentpartsofthewebapplicationyoudidinExercise50Ifyoucanbreakyourwebapplicationinpredictablewaysusingthediagramyoursquollstarttounderstandhowitworks

HowFormsWorkThebestwaytoplaywithformsistowritesomecodethatacceptsformdataandthenseewhatyoucandoTakeyourapppyfileandmakeitlooklikethis

Clickheretoviewcodeimage

form_testpy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hello)

8defindex()

9name=requestargsget(nameNobody)

10

11ifname

12greeting=fHelloname

13else

14greeting=HelloWorld

15

16returnrender_template(indexhtmlgreeting=greeting)

17

18if__name__==__main__

19apprun()Restartit(hitCTRL-Candthenrunitagain)to

makesureitloadsagainthenwithyourbrowsergoto

httplocalhost5000hellowhichshoulddisplayldquoIjustwantedto

sayHelloNobodyrdquoNextchangetheURLinyourbrowserto

httplocalhost5000helloname=Frankandyoursquollseeitsay

ldquoHelloFrankrdquoFinallychangethename=Frankparttobeyourname

Nowitrsquossayinghellotoyou

LetrsquosbreakdownthechangesImadetoyourscript1InsteadofjustastringforgreetingIrsquomnowusingrequestargstogetdatafromthebrowserThisisasimpledictthatcontainstheformvaluesaskey=valuepairs

2Ithenconstructthegreetingfromthenewnamewhichshouldbeveryfamiliartoyoubynow

3EverythingelseaboutthefileisthesameasbeforeYoursquorealsonotrestrictedtojustoneparameterontheURLChangethisexampletogivetwovariableslikethishttplocalhost5000helloname=Frankampgreet=HolaThenchangethecodetogetnameandgreetlikethisClickheretoviewcodeimage

greet=requestargsget(greetHello)

greeting=fgreetname

greeting=fgreetname

YoushouldalsotrynotgivingthegreetandnameparametersontheURLYoursquollsimplysendyourbrowsertohttplocalhost5000hellotoseethattheindexnowdefaultstoldquoNobodyrdquofornameandldquoHellordquoforgreet

CreatingHTMLFormsPassingtheparametersontheURLworksbutitrsquoskindofuglyandnoteasytouseforregularpeopleWhatyoureallywantisaldquoPOSTformrdquowhichisaspecialHTMLfilethathasaltformgttaginitThisformwillcollectinformationfromtheuserthensendittoyourwebapplicationjustlikeyoudidaboveLetrsquosmakeaquickonesoyoucanseehowitworksHerersquosthenewHTMLfileyouneedtocreateintemplateshello_formhtmlClickheretoviewcodeimage

hello_formhtml

lthtmlgt

ltheadgt

lttitlegtSampleWebFormlttitlegt

ltheadgt

ltbodygt

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

ltbodygt

lthtmlgtYoushouldthenchangeapppytolooklikethisClickhere

toviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hellomethods=[POSTGET])

8defindex()

9greeting=HelloWorld

10

11ifrequestmethod==POST

12name=requestform[name]

13greet=requestform[greet]

14greeting=fgreetname

15returnrender_template(indexhtmlgreeting=greeting)

16else

17returnrender_template(hello_formhtml)

18

19

20if__name__==__main__

21apprun()Onceyoursquovegotthosewrittenupsimplyrestart

thewebapplicationagainandhititwithyourbrowserlikebefore

ThistimeyoursquollgetaformaskingyouforldquoAGreetingrdquoandldquoYourNamerdquoWhenyouhittheSubmitbuttonontheformitwillgiveyouthesamegreetingyounormallygetbutthistimelookattheURLinyourbrowserSeehowitrsquoshttplocalhost5000helloeventhoughyousentinparametersThepartofthehello_formhtmlfilethatmakesthisworkisthelinewithltformaction=hellomethod=POSTgtThistellsyourbrowserto1Collectdatafromtheuserusingtheformfieldsinsidetheform

2SendthemtotheserverusingaPOSTtypeofrequestwhichisjustanotherbrowserrequestthatldquohidesrdquotheformfields

3SendthattothehelloURL(asshownintheaction=hellopart)

YoucanthenseehowthetwoltinputgttagsmatchthenamesofthevariablesinyournewcodeAlsonoticethatinsteadofjustaGETmethodinsideclassindexIhaveanothermethodPOSTHowthisnewapplicationworksisasfollows1Yourrequestgoestoindex()likenormalexceptnowthereisanif-statementthatcheckstherequestmethodforeitherPOSTorGETmethodsThisishowthebrowsertellsapppythatarequestiseitheraformsubmissionorURLparameters

2IfrequestmethodisPOSTthenyouprocesstheformasifitwerefilledoutandsubmittedreturningthepropergreeting

3Ifrequestmethodisanythingelsethenyousimplyreturnthehello_formhtmlfortheusertofillout

AsanexercisegointothetemplatesindexhtmlfileandaddalinkbacktojusthellosothatyoucankeepfillingouttheformandseeingtheresultsMakesureyoucanexplainhowthislinkworksandhowitrsquoslettingyoucyclebetweentemplatesindexhtmlandtemplateshello_formhtmlandwhatrsquosbeingruninsidethislatestPythoncode

CreatingaLayoutTemplateWhenyouworkonyourgameinthenextexerciseyoursquollneedtomakeabunchoflittleHTMLpagesWritingafullwebpageeachtimewillquicklybecometediousLuckilyyoucancreatealdquolayoutrdquotemplateorakindofshellthatwillwrapallyourotherpageswithcommonheadersandfootersGoodprogrammerstrytoreducerepetitionsolayoutsareessentialforbeingagoodprogrammerChangetemplatesindexhtmltobelikethisClickheretoviewcodeimage

index_laid_outhtml

extendslayouthtml

blockcontent

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

endblock

Thenchangetemplateshello_formhtmltobelikethisClickheretoviewcodeimage

hello_form_laid_outhtml

extendslayouthtml

blockcontent

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

endblock

AllwersquoredoingisstrippingouttheldquoboilerplaterdquoatthetopandthebottomwhichisalwaysoneverypageWersquollputthatbackintoasingletemplateslayouthtmlfilethathandlesitforusfromnowonOnceyouhavethosechangescreateatemplateslayouthtmlfilewiththisinitClickheretoviewcodeimage

layouthtml

lthtmlgt

ltheadgt

lttitlegtGothonsFromPlanetPercal25lttitlegt

ltheadgt

ltbodygt

blockcontent

endblock

ltbodygt

lthtmlgtThisfilelookslikearegulartemplateexceptthatitrsquos

goingtobepassedthecontentsoftheothertemplatesandusedto

wrapthemAnythingyouputinheredoesnrsquotneedtobeintheother

templatesYourotherHTMLtemplateswillbeinsertedintothe

blockcontentsectionflaskknowstousethislayouthtmlasthe

layoutbecauseyouputextendslayouthtmlatthetopofyour

templates

WritingAutomatedTestsforFormsItrsquoseasytotestawebapplicationwithyourbrowserbyjusthittingrefreshbutcomeonwersquoreprogrammershereWhydosomerepetitivetaskwhenwecanwritesomecodetotestourapplicationWhatyoursquoregoingtodonextiswritealittletestforyourwebapplicationformbasedonwhatyoulearnedinExercise

47IfyoudonrsquotrememberExercise47readitagainCreateanewfilenamedtestsapp_testspywiththisClickheretoviewcodeimage

app_testspy

1fromnosetoolsimport

2fromappimportapp

3

4appconfig[TESTING]=True

5web=apptest_client()

6

7deftest_index()

8rv=webget(follow_redirects=True)

9assert_equal(rvstatus_code404)

10

11rv=webget(hellofollow_redirects=True)

12assert_equal(rvstatus_code200)

13assert_in(bFillOutThisFormrvdata)

14

15data=nameZedgreetHola

16rv=webpost(hellofollow_redirects=Truedata=data)

17assert_in(bZedrvdata)

18assert_in(bHolarvdata)Finallyusenoseteststorun

thistestsetupandtestyourwebapplication$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0059s

OK

WhatIrsquomdoinghereisIrsquomactuallyimportingthewholeapplicationfromtheapppymodulethenrunningitmanuallyTheflaskframeworkhasaverysimpleAPIforprocessingrequestswhichlookslikethisClickheretoviewcodeimage

data=nameZedgreetHola

rv=webpost(hellofollow_redirects=Truedata=data)Thismeans

youcansendaPOSTrequestusingthepost()methodandthengiveit

theformdataasadictEverythingelseworksthesameastesting

webget()requests

Inthetestsapp_testspyautomatedtestIrsquomfirstmakingsuretheURLreturnsaldquo404NotFoundrdquoresponsesinceitactuallydoesnrsquotexistThenIrsquomcheckingthathelloworkswithbothaGETandaPOSTformFollowing

thetestshouldbefairlysimpleevenifyoumightnottotallyknowwhatrsquosgoingonTakesometimestudyingthislatestapplicationespeciallyhowtheautomatedtestingworksMakesureyouunderstandhowIimportedtheapplicationfromapppyandranitdirectlyfortheautomatedtestThisisanimportanttrickthatwillleadtomorelearning

StudyDrills1ReadevenmoreaboutHTMLandgivethesimpleformabetterlayoutIthelpstodrawwhatyouwanttodoonpaperandthenimplementitwithHTML

2Thisoneishardbuttrytofigureouthowyoursquoddoafileuploadformsothatyoucanuploadanimageandsaveittothedisk

3Thisisevenmoremind-numbingbutgofindtheHTTPRFC(whichisthedocumentthatdescribeshowHTTPworks)andreadasmuchofitasyoucanItisreallyboringbutcomesinhandyonceinawhile

4ThiswillalsobereallydifficultbutseeifyoucanfindsomeonetohelpyousetupawebserverlikeApacheNginxorthttpdTrytoserveacoupleofyourhtmlandcssfileswithitjusttoseeifyoucanDonrsquotworryifyoucanrsquotWebserverskindofsuck

5Takeabreakafterthisandjusttrymakingasmanydifferentwebapplicationsasyoucan

BreakingItThisisagreatplacetofigureouthowtobreakwebapplicationsYoushouldexperimentwiththefollowing

1HowmuchdamagecanyoudowiththeFLASK_DEBUGsettingonBecarefulthatyoudonrsquotwipeyourselfoutdoingthis

2LetrsquossayyoudonrsquothavedefaultparametersfortheformsWhatcouldgowrong

3YoursquorecheckingforPOSTandthenldquoanythingelserdquoYoucanusethecurlcommandlinetooltogeneratedifferentrequesttypesWhathappens

Exercise52TheStartofYourWebGame

WersquorecomingtotheendofthebookandinthisexerciseIrsquomgoingtoreallychallengeyouWhenyoursquoredoneyoursquollbeareasonablycompetentPythonbeginnerYoursquollstillneedtogothroughafewmorebooksandwriteacouplemoreprojectsbutyoursquollhavetheskillstocompletethemTheonlyobstacleswillbetimemotivationandresourcesInthisexercisewewonrsquotmakeacompletegamebutinsteadwersquollmakeanldquoenginerdquothatcanrunthegamefromExercise47inthebrowserThiswillinvolverefactoringExercise43mixinginthestructurefromExercise47addingautomatedtestsandfinallycreatingawebenginethatcanrunthegamesThisexercisewillbehugeandIpredictyoucouldspendanywherefromaweektomonthsonitbeforemovingonItrsquosbesttoattackitinlittlechunksanddoabitanighttakingyourtimetomakeeverythingworkbeforemovingon

RefactoringtheExercise43GameYoursquovebeenalteringthegothonwebprojectfortwoexercisesandyoursquolldoitonemoretimeinthisexerciseTheskillyoursquorelearningiscalledldquorefactoringrdquoorasIliketocallitldquofixingstuffrdquoRefactoringisatermprogrammersusetodescribetheprocessoftakingoldcodeandchangingittohavenewfeaturesorjusttocleanitupYoursquovebeendoingthiswithoutevenknowingitasitrsquossecondnaturetobuildingsoftwareWhatyoursquolldointhispartistaketheideasfromExercise47ofatestableldquomaprdquoofRoomsandthegamefromExercise43andcombinethemtogethertocreateanewgamestructureItwillhavethesamecontentjustldquorefactoredrdquotohaveabetterstructureThefirststepistograbthecodefromex47gamepycopyittogothonwebplanispherepycopythetestsex47_testspyfiletotestsplanisphere_testspyandrunnosetestsagaintomakesureitkeepsworkingThewordldquoplanisphererdquoisjustasynonymforldquomaprdquowhichavoidsPythonrsquosbuilt-inmapfunctionThethesaurusisyourfriend

WarningFromnowonIwonrsquotshowyoutheoutputofatestrunJustassumethatyoushouldbedoingitanditrsquolllookliketheprecedingunlessyouhaveanerror

OnceyouhavethecodefromExercise47copiedoveritrsquostimetorefactorittohavetheExercise43mapinitIrsquomgoingtostartoffbylayingdownthebasicstructureandthenyoursquollhaveanassignmenttomaketheplanispherepyfileandtheplanisphere_testspyfilecompleteLayoutthebasicstructureofthemapusingtheRoomclassasitisnowClickheretoviewcodeimage

planispherepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)

13

14

15central_corridor=Room(CentralCorridor

16

17TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyed

18yourentirecrewYouarethelastsurvivingmemberandyour

last

19missionistogettheneutrondestructbombfromtheWeapons

Armoryput

20itinthebridgeandblowtheshipupaftergettingintoan

escapepod

21

22YourerunningdownthecentralcorridortotheWeaponsArmory

whena

23Gothonjumpsoutredscalyskindarkgrimyteethandevil

clown

24costumeflowingaroundhishatefilledbodyHesblocking

thedoorto

25theArmoryandabouttopullaweapontoblastyou

26)

27

28

29laser_weapon_armory=Room(LaserWeaponArmory

30

31LuckyforyoutheymadeyoulearnGothoninsultsinthe

academyYou

32telltheoneGothonjokeyouknowLbhezbgurevffbsngjura

furfvgf

33nebhaqgurubhfrfurfvgfnebhaqgurubhfrTheGothon

stopstries

34nottolaughthenbustsoutlaughingandcantmoveWhile

hes

35laughingyourunupandshoothimsquareintheheadputting

himdown

36thenjumpthroughtheWeaponArmorydoor

37

38YoudoadiverollintotheWeaponArmorycrouchandscanthe

roomfor

39moreGothonsthatmightbehidingItsdeadquiettoo

quietYou

40standupandruntothefarsideoftheroomandfindthe

neutronbomb

41initscontainerTheresakeypadlockontheboxandyou

needthe

42codetogetthebomboutIfyougetthecodewrong10times

thenthe

43lockclosesforeverandyoucantgetthebombThecodeis3

digits

44)

45

46

47the_bridge=Room(TheBridge

48

49Thecontainerclicksopenandthesealbreakslettinggas

outYou

50grabtheneutronbombandrunasfastasyoucantothebridge

whereyou

51mustplaceitintherightspot

52

53YouburstontotheBridgewiththenetrondestructbombunder

yourarm

54andsurprise5Gothonswhoaretryingtotakecontrolofthe

shipEach

55ofthemhasanevenuglierclowncostumethanthelastThey

havent

56pulledtheirweaponsoutyetastheyseetheactivebomb

underyourarm

57anddontwanttosetitoff

58)

59

60

61escape_pod=Room(EscapePod

62

63Youpointyourblasteratthebombunderyourarmandthe

Gothonsput

64theirhandsupandstarttosweatYouinchbackwardtothe

dooropen

65itandthencarefullyplacethebombonthefloorpointing

your

66blasteratitYouthenjumpbackthroughthedoorpunchthe

close

67buttonandblastthelocksotheGothonscantgetoutNow

thatthe

68bombisplacedyouruntotheescapepodtogetoffthistin

can

69

70Yourushthroughtheshipdesperatelytryingtomakeittothe

escape

71podbeforethewholeshipexplodesItseemslikehardlyany

Gothons

72areontheshipsoyourrunisclearofinterferenceYou

gettothe

73chamberwiththeescapepodsandnowneedtopickoneto

takeSomeof

74themcouldbedamagedbutyoudonthavetimeto

lookTheres5pods

75whichonedoyoutake

76)

77

78

79the_end_winner=Room(TheEnd

80

81Youjumpintopod2andhittheejectbuttonThepodeasily

slidesout

82intospaceheadingtotheplanetbelowAsitfliestothe

planetyou

83lookbackandseeyourshipimplodethenexplodelikeabright

star

84takingouttheGothonshipatthesametimeYouwon

85)

86

87

88the_end_loser=Room(TheEnd

89

90YoujumpintoarandompodandhittheejectbuttonThepod

escapes

91outintothevoidofspacethenimplodesasthehull

rupturescrushing

92yourbodyintojamjelly

93

94)

95

96escape_podadd_paths(

972the_end_winner

98the_end_loser

99)

100

101generic_death=Room(deathYoudied)

102

103the_bridgeadd_paths(

104throwthebombgeneric_death

105slowlyplacethebombescape_pod

106)

107

108laser_weapon_armoryadd_paths(

1090132the_bridge

110generic_death

111)

112

113central_corridoradd_paths(

114shootgeneric_death

115dodgegeneric_death

116tellajokelaser_weapon_armory

117)

118

119START=central_corridor

120

121defload_room(name)

122

123Thereisapotentialsecurityproblemhere

124WhogetstosetnameCanthatexposeavariable

125

126returnglobals()get(name)

127

128defname_room(room)

129

130SamepossiblesecurityproblemCanyoutrustroom

131Whatsabettersolutionthanthisglobalslookup

132

133forkeyvalueinglobals()items()

134ifvalue==room

135returnkeyYoursquollnoticethatthereareacouple

ofproblemswithourRoomclassandthismap1Wehavetoputthe

textthatwasintheif-elseclausesthatgotprintedbeforeentering

aroomaspartofeachroomThismeansyoucanrsquotshufflethe

planispherearoundwhichwouldbeniceYoursquollbefixingthatupin

thisexercise

2TherearepartsintheoriginalgamewherewerancodethatdeterminedthingslikethebombrsquoskeypadcodeortherightpodInthisgamewejustpicksomedefaultsandgowithitbutlateryoursquollbegivenStudyDrillstomakethisworkagain

3Irsquovejustmadeageneric_deathendingforallofthebaddecisionswhichyoursquollhavetofinishformeYoursquollneedtogobackthroughandaddinalltheoriginalendingsandmakesuretheywork

4Irsquovegotanewkindoftransitionlabeledthatwillbeusedforaldquocatch-allrdquoactionintheengine

Onceyoursquovegotthatbasicallywrittenoutherersquosthenewautomatedtesttestsplanisphere_testpythatyoushouldhavetogetyourselfstartedClickheretoviewcodeimage

planisphere_testspy

1fromnosetoolsimport

2fromgothonwebplanisphereimport

3

4deftest_room()

5gold=Room(GoldRoom

6Thisroomhasgoldinityoucangrab

Theresa

7doortothenorth)

8assert_equal(goldnameGoldRoom)

9assert_equal(goldpaths)

10

11deftest_room_paths()

12center=Room(CenterTestroominthecenter)

13north=Room(NorthTestroominthenorth)

14south=Room(SouthTestroominthesouth)

15

16centeradd_paths(northnorthsouthsouth)

17assert_equal(centergo(north)north)

18assert_equal(centergo(south)south)

19

20deftest_map()

21start=Room(StartYoucangowestanddownahole)

22west=Room(TreesTherearetreeshereyoucango

east)

23down=Room(DungeonItsdarkdownhereyoucango

up)

24

25startadd_paths(westwestdowndown)

26westadd_paths(eaststart)

27downadd_paths(upstart)

28

29assert_equal(startgo(west)west)

30assert_equal(startgo(west)go(east)start)

31assert_equal(startgo(down)go(up)start)

32

33deftest_gothon_game_map()

34start_room=load_room(START)

35assert_equal(start_roomgo(shoot)generic_death)

36assert_equal(start_roomgo(dodge)generic_death)

37

38room=start_roomgo(tellajoke)

39assert_equal(roomlaser_weapon_armory)Yourtaskinthis

partoftheexerciseistocompletethemapandmaketheautomated

testcompletelyvalidatethewholemapThisincludesfixingallthe

generic_deathobjectstoberealendingsMakesurethisworksreally

wellandthatyourtestisascompleteaspossiblebecausewersquollbe

changingthismaplaterandyoursquollusetheteststomakesureit

keepsworking

CreatinganEngineYoushouldhaveyourgamemapworkingandagoodunittestforitInowwantyoutomakeasimplelittlegameenginethatwillruntheroomscollectinputfromtheplayerandkeeptrackofwhereaplayerisinthegameWersquollbeusingthesessionsyoujustlearnedtomakeasimplegameenginethatwilldothefollowing

1Startanewgamefornewusers2Presenttheroomtotheuser3Takeinputfromtheuser4Runuserinputthroughthegame5Displaytheresultsandkeepgoinguntiltheuserdies

Todothisyoursquoregoingtotakethetrustyapppyyoursquovebeenhackingonandcreateafullyworkingsession-basedgameengineThecatchisIrsquomgoingtomakeaverysimpleonewithbasicHTMLfilesanditrsquollbeuptoyoutocompleteitHerersquosthebaseengineClickheretoviewcodeimage

apppy

1fromflaskimportFlasksessionredirecturl_forescape

request

2fromflaskimportrender_template

3fromgothonwebimportplanisphere

4

5app=Flask(__name__)

6

7approute()

8defindex()

9thisisusedtosetupthesessionwithstartingvalues

10session[room_name]=planisphereSTART

11returnredirect(url_for(game))

12

13approute(gamemethods=[GETPOST])

14defgame()

15room_name=sessionget(room_name)

16

17ifrequestmethod==GET

18ifroom_name

19room=planisphereload_room(room_name)

20returnrender_template(show_roomhtmlroom=room)

21else

22whyisthereheredoyouneedit

23returnrender_template(you_diedhtml)

24else

25action=requestformget(action)

26

27ifroom_nameandaction

28room=planisphereload_room(room_name)

29next_room=roomgo(action)

30

31ifnotnext_room

32session[room_name]=

planispherename_room(room)

33else

34session[room_name]=

planispherename_room(next_room)

35

36returnredirect(url_for(game))

37

38

39YOUSHOULDCHANGETHISIFYOUPUTONTHEINTERNET

40appsecret_key=A0Zr98j3yXR~XHHjmN]LWXRT

41

42if__name__==__main__

43apprun()Thereareevenmorenewthingsinthisscript

butamazinglyitrsquosanentireweb-basedgameengineinasmallfile

BeforeyourunapppyyouneedtochangeyourPYTHONPATHenvironment

variableDonrsquotknowwhatthatisIknowitrsquoskindofdumbbutyou

havetolearnwhatthisistorunevenbasicPythonprogramsthatrsquos

howPythonpeoplelikethings

InyourTerminaltypeClickheretoviewcodeimageexportPYTHONPATH=$PYTHONPATH

OnWindowsPowerShelldoClickheretoviewcodeimage$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

YoushouldonlyhavetodoitoncepershellsessionbutifyougetanimporterrorthenyouprobablyneedtodothisoryoudiditwrongYoushouldnextdeletetemplateshello_formhtmlandtemplatesindexhtmlandcreatethetwotemplatesmentionedintheprecedingcodeHerersquosaverysimpletemplatesshow_roomhtmlClickheretoviewcodeimage

show_roomhtml

extendslayouthtml

blockcontent

lth1gtroomnamelth1gt

ltpregt

roomdescription

ltpregt

ifroomnamein[deathTheEnd]

ltpgtltahref=gtPlayAgainltagtltpgt

else

ltpgt

ltformaction=gamemethod=POSTgt

-ltinputtype=textname=actiongtltinputtype=SUBMITgt

ltformgt

ltpgt

endif

endblock

ThatisthetemplatetoshowaroomasyoutravelthroughthegameNextyouneedonetotellsomeonetheydiedinthecasethattheygottotheendofthemaponaccidentwhichistemplatesyou_diedhtmlClickheretoviewcodeimage

you_diedhtml

lth1gtYouDiedlth1gt

ltpgtLookslikeyoubitthedustltpgt

ltpgtltahref=gtPlayAgainltagtltpgtWiththoseinplaceyoushouldnow

beabletodothefollowing1Getthetesttestsapp_testspy

workingagainsothatyouaretestingthegameYouwonrsquotbeableto

domuchmorethanafewclicksinthegamebecauseofsessionsbut

youshouldbeabletodosomebasics

2Runthepython36apppyscriptandtestoutthegameYoushouldbeabletorefreshandfixthegamelikenormalYoushouldalsobeabletoworkwiththegameHTMLandengineuntilitdoesallthethingsyouwantittodo

YourFinalExamDoyoufeellikethiswasahugeamountofinformationthrownatyouallatonceGoodIwantyoutohavesomethingtotinkerwithwhileyoubuildyourskillsTocompletethisexerciseIrsquomgoingtogiveyouafinalsetoftasksforyoutocompleteonyourownYoursquollnoticethatwhatyoursquovewrittensofarisnrsquotverywellbuiltitisjustafirstversionofthecodeYourjobnowistomakethegamemorecompletebydoingthesethings

1FixallthebugsImentioninthecodeandanythatIdidnrsquotmentionIfyoufindnewbugsletmeknow

2Improvealloftheautomatedtestssothatyoutestmoreoftheapplicationandgettoapointwhereyouuseatestratherthanyourbrowsertochecktheapplicationwhileyouwork

3MaketheHTMLlookbetter4Researchloginsandcreateasignupsystemfortheapplicationsopeoplecanhaveloginsandhighscores

5Completethegamemapmakingitaslargeandfeature-completeaspossible

6Givepeoplealdquohelprdquosystemthatletsthemaskwhattheycandoateachroominthegame

7Addanyotherfeaturesyoucanthinkoftothegame8CreateseveralldquomapsrdquoandletpeoplechooseagametheywanttorunYourapppyengineshouldbeabletorunanymapofroomsyougiveitsoyoucansupportmultiplegames

9FinallyusewhatyoulearnedinExercises48and49tocreateabetterinputprocessorYouhavemostofthecodenecessaryyoujustneedtoimprovethegrammarandhookituptoyourinputformandtheGameEngine

Goodluck

Goodluck

CommonStudentQuestionsIrsquomusingsessionsinmygameandIcanrsquottestitwithnosetestsReadtheFlaskTestingDocumentationaboutldquoOtherTestingTricksrdquo(httpflaskpocooorgdocs012testingother-testing-tricks)forinformationoncreatingfakesessionsinsideyourtests

IgetanImportErrorItcouldbeoneormoreofthesewrongdirectorywrongPythonversionPYTHONPATHnotsetno__init__pyfileandorspellingmistakeinimport

NextSteps

YoursquorenotaprogrammerquiteyetIliketothinkofthisbookasgivingyouyourldquoprogrammingblackbeltrdquoYouknowenoughtostartanotherbookonprogrammingandhandleitjustfineThisbookshouldhavegivenyouthementaltoolsandattitudeyouneedtogothroughmostPythonbooksandactuallylearnsomethingItmightevenmakeiteasyIrecommendyoucheckoutsomeoftheseprojectsandtrytobuildsomethingwiththem

bullLearnRubyTheHardWay(httpslearnrubythehardwayorg)YouwilllearnevenmoreaboutprogrammingasyoulearnmoreprogramminglanguagessotrylearningRubytoo

bullTheDjangoTutorial(httpsdocsdjangoprojectcomen111intro)BuildawebapplicationwiththeDjangowebframework

bullSciPy(httpswwwscipyorg)Checkthisoutifyoursquoreintosciencemathandengineering

bullPyGame(httpwwwpygameorg)MakeagamewithgraphicsandsoundbullPandas(httppandaspydataorg)Usethisfordoingdatamanipulationandanalysis

bullNaturalLanguageToolkit(httpwwwnltkorg)Usethisforanalyzingwrittentextandwritingthingslikespamfiltersandchatbots

bullTensorFlow(httpswwwtensorfloworg)Usethisformachinelearningandvisualization

bullRequests(httpdocspython-requestsorg)LearntheclientsideofHTTPandtheweb

bullScraPy(httpsscrapyorg)Tryscrapingsomewebsitestogetinformationoffthem

bullKivy(httpskivyorg)Createuserinterfacesondesktopsandmobileplatforms

bullLearnCTheHardWay(httpslearncodethehardwayorg)AfteryoursquorefamiliarwithPythontrylearningCandalgorithmswithmyotherbookTakeitslowCisdifferentbutaverygoodthingtolearn

PickoneoftheprecedingresourcesandgothroughanytutorialsanddocumentationtheyhaveAsyougothroughdocumentationwithcodeinittype

inallofthecodeandmakeitworkThatrsquoshowIdoitThatrsquoshoweveryprogrammerdoesitReadingprogrammingdocumentationisnotenoughtolearnityouhavetodoitAfteryougetthroughthetutorialandanyotherdocumentationtheyhavemakesomethingAnythingwilldoevensomethingsomeoneelsehasalreadywrittenJustmakesomethingJustunderstandanythingyouwritewillprobablysuckThatrsquosalrightthoughIsuckateveryprogramminglanguageatfirstNobodywritespureperfectgoldwhentheyrsquoreabeginnerandanyonewhotellsyoutheydidisahugeliar

HowtoLearnAnyProgrammingLanguageIrsquomgoingtoteachyouhowtolearnmostoftheprogramminglanguagesyoumaywanttolearninthefutureTheorganizationofthisbookisbasedonhowIandmanyotherprogrammerslearnnewlanguagesTheprocessthatIusuallyfollowisasfollows

1Getabookorsomeintroductorytextaboutthelanguage2Gothroughthebookandtypeinallofthecodemakingallofitrun3Readthebookasyouworkonthecodetakingnotes4Usethelanguagetoimplementasmallsetofprogramsyouarefamiliarwithinanotherlanguage

5ReadotherpeoplersquoscodeinthelanguageandtrytocopytheirpatternsInthisbookIforcedyoutogothroughthisprocessveryslowlyandinsmallchunksOtherbooksarenrsquotorganizedthesamewayandthismeansyouhavetoextrapolatehowIrsquovemadeyoudothistohowtheircontentisorganizedThebestwaytodothisistoreadthebooklightlyandmakealistofallthemajorcodesectionsTurnthislistintoasetofexercisesbasedonthechaptersandthensimplydotheminorderoneatatimeTheprecedingprocessalsoworksfornewtechnologiesassumingtheyhavebooksyoucanreadForanythingwithoutbooksyoudotheaboveprocessbutuseonlinedocumentationorsourcecodeasyourinitialintroductionEachnewlanguageyoulearnmakesyouabetterprogrammerandasyoulearnmorelanguagestheybecomeeasiertolearnByyourthirdorfourthlanguageyoushouldbeabletopickupsimilarlanguagesinaweekwithstrangerlanguagestakinglongerNowthatyouknowPythonyoucouldpotentiallylearnRubyandJavaScriptfairlyquicklybycomparisonThisissimplybecausemanylanguagessharesimilarconceptsandonceyoulearntheconceptsinonelanguagetheyworkinothersThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbea

ThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbeastupidtouristAstupidtouristissomeonewhogoestoanothercountryandthencomplainsthatthefoodisnrsquotlikethefoodathome(ldquoWhycanrsquotIgetagoodburgerinthisstupidcountryrdquo)WhenyoursquorelearninganewlanguageassumethatwhatitdoesisnrsquotstupiditrsquosjustdifferentandembraceitsoyoucanlearnitAfteryoulearnalanguagethoughdonrsquotbeaslavetothatlanguagersquoswayofdoingthingsSometimesthepeoplewhousealanguageactuallydosomeveryidioticthingsfornootherreasonthanldquothatrsquoshowwersquovealwaysdoneitrdquoIfyoulikeyourstylebetterandyouknowhoweveryoneelsedoesitthenfeelfreetobreaktheirrulesifitimprovesthingsIreallyenjoylearningnewprogramminglanguagesIthinkofmyselfasaldquoprogrammeranthropologistrdquoandthinkoflanguagesaslittleinsightsaboutthegroupofprogrammerswhousethemIrsquomlearningalanguagetheyallusetotalktoeachotherthroughcomputersandIfindthisfascinatingThenagainIrsquomkindofaweirdguysojustlearnprogramminglanguagesbecauseyouwanttoEnjoyThisisreallyfunstuff

AdvicefromanOldProgrammer

YoursquovefinishedthisbookandhavedecidedtocontinuewithprogrammingMaybeitwillbeacareerforyouormaybeitwillbeahobbyYoursquollneedsomeadvicetomakesureyoucontinueontherightpathandgetthemostenjoymentoutofyournewlychosenactivityIrsquovebeenprogrammingforaverylongtimeSolongthatitrsquosincrediblyboringtomeAtthetimethatIwrotethisbookIknewabout20programminglanguagesandcouldlearnnewonesinaboutadaytoaweekdependingonhowweirdtheywereEventuallythoughthisjustbecameboringandcouldnrsquotholdmyinterestanymoreThisdoesnrsquotmeanIthinkprogrammingisboringorthatyouwillthinkitrsquosboringonlythatIfindituninterestingatthispointinmyjourneyWhatIdiscoveredafterthisjourneyoflearningisthatitrsquosnotthelanguagesthatmatterbutwhatyoudowiththemActuallyIalwaysknewthatbutIrsquodgetdistractedbythelanguagesandforgetitperiodicallyNowIneverforgetitandneithershouldyouWhichprogramminglanguageyoulearnandusedoesnrsquotmatterDonotgetsuckedintothereligionsurroundingprogramminglanguagesasthatwillonlyblindyoutotheirtruepurposeofbeingyourtoolfordoinginterestingthingsProgrammingasanintellectualactivityistheonlyartformthatallowsyoutocreateinteractiveartYoucancreateprojectsthatotherpeoplecanplaywithandyoucantalktothemindirectlyNootherartformisquitethisinteractiveMoviesflowtotheaudienceinonedirectionPaintingsdonotmoveCodegoesbothwaysProgrammingasaprofessionisonlymoderatelyinterestingItcanbeagoodjobbutyoucouldmakeaboutthesamemoneyandbehappierrunningafastfoodjointYoursquoremuchbetteroffusingcodeasyoursecretweaponinanotherprofessionPeoplewhocancodeintheworldoftechnologycompaniesareadimeadozenandgetnorespectPeoplewhocancodeinbiologymedicinegovernmentsociologyphysicshistoryandmathematicsarerespectedandcandoamazingthingstoadvancethosedisciplinesOfcourseallofthisadviceispointlessIfyoulikedlearningtowritesoftwarewiththisbookyoushouldtrytouseittoimproveyourlifeanywayyoucanGooutandexplorethisweirdwonderfulnewintellectualpursuitthatbarelyanyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhile

anyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhileyoucanFinallyIrsquollsaythatlearningtocreatesoftwarechangesyouandmakesyoudifferentNotbetterorworsejustdifferentYoumayfindthatpeopletreatyouharshlybecauseyoucancreatesoftwaremaybeusingwordslikeldquonerdrdquoMaybeyoursquollfindthatbecauseyoucandissecttheirlogictheyhatearguingwithyouYoumayevenfindthatsimplyknowinghowacomputerworksmakesyouannoyingandweirdtothemTothisIhavejustonepieceofadvicetheycangotohellTheworldneedsmoreweirdpeoplewhoknowhowthingsworkandwholovetofigureitalloutWhentheytreatyoulikethisjustrememberthatthisisyourjourneynottheirsBeingdifferentisnotacrimeandpeoplewhotellyouitisarejustjealousthatyoursquovepickedupaskilltheyneverintheirwildestdreamscouldacquireYoucancodeTheycannotThatisprettydamncool

AppendixCommandLineCrashCourse

ThisappendixisasuperfastcourseinusingthecommandlineItisintendedtobedonerapidlyinaboutadayortwoandnotmeanttoteachyouadvancedshellusage

IntroductionShutUpandShellThisappendixisacrashcourseinusingthecommandlinetomakeyourcomputerperformtasksAsacrashcourseitrsquosnotasdetailedorextensiveasmyotherbooksItissimplydesignedtogetyoubarelycapableenoughtostartusingyourcomputerlikearealprogrammerdoesWhenyoursquoredonewiththisappendixyouwillbeabletogivemostofthebasiccommandsthateveryshellusertoucheseverydayYoursquollunderstandthebasicsofdirectoriesandafewotherconceptsTheonlypieceofadviceIamgoingtogiveyouisthis

ShutupandtypeallofthisinSorrytobemeanbutthatrsquoswhatyouhavetodoIfyouhaveanirrationalfearofthecommandlinetheonlywaytoconqueranirrationalfearistojustshutupandfightthroughitYouarenotgoingtodestroyyourcomputerYouarenotgoingtobethrownintosomejailatthebottomofMicrosoftrsquosRedmondcampusYourfriendswonrsquotlaughatyouforbeinganerdSimplyignoreanystupidweirdreasonsyouhaveforfearingthecommandlineWhyBecauseifyouwanttolearntocodethenyoumustlearnthisProgramminglanguagesareadvancedwaystocontrolyourcomputerwithlanguageThecommandlineisthebabybrotherofprogramminglanguagesLearningthecommandlineteachesyoutocontrolthecomputerusinglanguageOnceyougetpastthatyoucanthenmoveontowritingcodeandfeelinglikeyouactuallyownthehunkofmetalyoujustbought

HowtoUseThisAppendixThebestwaytousethisappendixistodothefollowing

bullGetyourselfasmallpapernotebookandapenbullStartatthebeginningoftheappendixanddoeachexerciseexactlyasyoursquoretold

bullWhenyoureadsomethingthatdoesnrsquotmakesenseorthatyoudonrsquotunderstandwriteitdowninyournotebookLeavealittlespacesoyoucanwriteananswer

bullAfteryoufinishanexercisegobackthroughyournotebookandreviewthequestionsyouhaveTrytoanswerthembysearchingonlineandaskingfriendswhomightknowtheanswerEmailmeathelplearncodethehardwayorgandIrsquollhelpyoutoo

JustkeepgoingthroughthisprocessofdoinganexercisewritingdownquestionsyouhavethengoingbackthroughandansweringthequestionsyoucanBythetimeyoursquoredoneyoursquollactuallyknowalotmorethanyouthinkaboutusingthecommandline

YouWillBeMemorizingThingsIrsquomwarningyouaheadoftimethatIrsquomgoingtomakeyoumemorizethingsrightawayThisisthequickestwaytogetyoucapableatsomethingbutforsomepeoplememorizationispainfulJustfightthroughitanddoitanywayMemorizationisanimportantskillinlearningthingssoyoushouldgetoveryourfearofitHerersquoshowyoumemorizethings

bullTellyourselfyouwilldoitDonrsquottrytofindtricksoreasywaysoutofitjustsitdownanddoit

bullWritewhatyouwanttomemorizeonsomeindexcardsPutonehalfofwhatyouneedtolearnononesidethenanotherhalfontheotherside

bullEverydayforabout15to30minutesdrillyourselfontheindexcardstryingtorecalleachonePutanycardsyoudonrsquotgetrightintoadifferentpilejustdrillthosecardsuntilyougetboredthentrythewholedeckandseeifyouimprove

bullBeforeyougotobeddrilljustthecardsyougotwrongforabout5minutesthengotosleep

ThereareothertechniqueslikeyoucanwritewhatyouneedtolearnonasheetofpaperlaminateitthenstickittothewallofyourshowerWhileyoursquorebathingdrilltheknowledgewithoutlookingandwhenyougetstuckglanceatittorefreshyourmemoryIfyoudothiseverydayyoushouldbeabletomemorizemostthingsItellyoutomemorizeinaboutaweektoamonthOnceyoudonearlyeverythingelsebecomeseasierandintuitivewhichisthepurposeofmemorizationItrsquosnottoteachyouabstractconceptsbutrathertoingrainthebasicssothattheyareintuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthese

intuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthesebasicstheystopbeingspeedbumpspreventingyoufromlearningmoreadvancedabstractconcepts

TheSetupInthisappendixyouwillbeinstructedtodothreethings

bullDosomethingsinyourshell(commandlineTerminalPowerShell)bullLearnaboutwhatyoujustdidbullDomoreonyourown

ForthisfirstexerciseyoursquollbeexpectedtogetyourTerminalopenandworkingsothatyoucandotherestoftheappendix

DoThisGetyourTerminalshellorPowerShellworkingsoyoucanaccessitquicklyandknowthatitworksmacOS

FormacOSyoursquollneedtodothisbullHolddownthecommandkeyandhitthespacebarbullAsearchbarwillpopupbullTypeTerminalbullClickontheTerminalapplicationthatlookskindoflikeablackboxbullThiswillopenTerminalbullYoucannowgotoyourdockandCTRL-clicktopullupthemenuthenselectOptionsrarrKeepIndock

NowyouhaveyourTerminalopenanditrsquosinyourdocksoyoucangettoitLinux

IrsquomassumingthatifyouhaveLinuxthenyoualreadyknowhowtogetatyourTerminalLookthroughthemenuforyourwindowmanagerforanythingnamedldquoShellrdquoorldquoTerminalrdquoWindows

OnWindowswersquoregoingtousePowerShellPeopleusedtoworkwithaprogramcalledcmdexebutitrsquosnotnearlyasusableasPowerShellIfyouhaveWindows7orlaterdothis

bullClickStartbullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquo

bullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquobullHitEnter

IfyoudonrsquothaveWindows7youshouldseriouslyconsiderupgradingIfyoustillinsistonnotupgradingthenyoucantryinstallingPowerShellfromMicrosoftrsquosdownloadcenterSearchonlinetofindldquopowershelldownloadsrdquoforyourversionofWindowsYouareonyourownthoughsinceIdonrsquothaveWindowsXPbuthopefullythePowerShellexperienceisthesame

YouLearnedThisYoulearnedhowtogetyourTerminalopensoyoucandotherestofthisappendix

WarningIfyouhavethatreallysmartfriendwhoalreadyknowsLinuxignoreherwhenshetellsyoutousesomethingotherthanBashIrsquomteachingyouBashThatrsquositShewillclaimthatzshwillgiveyou30moreIQpointsandwinyoumillionsinthestockmarketIgnoreherYourgoalistogetcapableenoughandatthislevelitdoesnrsquotmatterwhichshellyouuseThenextwarningisstayoffIRCorotherplaceswhereldquohackersrdquohangoutTheythinkitrsquosfunnytohandyoucommandsthatcandestroyyourcomputerThecommandrm-rfisaclassicthatyoumustnevertypeJustavoidthemIfyouneedhelpmakesureyougetitfromsomeoneyoutrustandnotfromrandomidiotsontheinternet

DoMoreThisexercisehasalargeldquodomorerdquopartTheotherexercisesarenotasinvolvedasthisonebutIrsquomhavingyouprimeyourbrainfortherestoftheappendixbydoingsomememorizationJusttrustmethiswillmakethingssilkysmoothlateronLinuxmacOS

TakethislistofcommandsandcreateindexcardswiththenamesontheleftononesideandthedefinitionsontheothersideDrillthemeverydaywhilecontinuingwiththelessonsinthisappendix

pwdprintworkingdirectoryhostnamemycomputerrsquosnetworkname

mkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectorymvmoveafileordirectorylesspagethroughafilecatprintthewholefilexargsexecuteargumentsfindfindfilesgrepfindthingsinsidefilesmanreadamanualpageaproposfindwhichmanualpageisappropriateenvlookatyourenvironmentechoprintsomeargumentsexportexportsetanewenvironmentvariableexitexittheshellsudoDANGERbecomesuperuserrootDANGER

Windows

IfyoursquoreusingWindowsthenherersquosyourlistofcommandspwdprintworkingdirectoryhostnamemycomputerrsquosnetworknamemkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectory

robocopyrobustcopymvmoveafileordirectorymorepagethroughafiletypeprintthewholefileforfilesrunacommandonlotsoffilesdir-rfindfilesselect-stringfindthingsinsidefileshelpreadamanualpagehelpctrfindwhatmanualpageisappropriateechoprintsomeargumentssetexportsetanewenvironmentvariableexitexittheshellrunasDANGERbecomesuperuserrootDANGER

DrilldrilldrillDrilluntilyoucansaythesephrasesrightawaywhenyouseethatwordThendrilltheinversesothatyoureadthephraseandknowwhatcommandwilldothatYoursquorebuildingyourvocabularybydoingthisbutdonrsquotspendsomuchtimeyougonutsandgetbored

PathsFoldersDirectories(pwd)Inthisexerciseyoulearnhowtoprintyourworkingdirectorywiththepwdcommand

DoThisIrsquomgoingtoteachyouhowtoreadtheseldquosessionsrdquothatIshowyouYoudonrsquothavetotypeeverythingIlistherejustsomeoftheparts

bullYoudonottypeinthe$(Unix)orlt(Windows)ThatrsquosjustmeshowingyoumysessionsoyoucanseewhatIgot

bullYoutypeinthestuffafter$orltthenhitEnterSoifIhave$pwdyoutypejustpwdandhitEnter

bullYoucanthenseewhatIhaveforoutputfollowedbyanother$orltpromptThatcontentistheoutputandyoushouldseethesameoutput

LetrsquosdoasimplefirstcommandsoyoucangetthehangofthisLinuxmacOS

Exercise2Session

$pwd

Userszedshaw

$

Windows

Exercise2WindowsSession

PSCUserszedgtpwd

Path

----

CUserszed

PSCUserszedlt

WarningInthisappendixIneedtosavespacesothatyoucanfocusontheimportantdetailsofthecommandsTodothisIrsquomgoingtostripoutthefirstpartoftheprompt(thePSCUserszedabove)andleavejustthelittlegtpartThismeansyourpromptwonrsquotlookexactlythesamebutdonrsquotworryaboutthatRememberthatfromnowonIrsquollonlyhavethegttotellyouthatrsquosthepromptIrsquomdoingthesamethingfortheUnixpromptsbutUnixpromptsaresovariedthatmostpeoplegetusedto$meaningldquojustthepromptrdquo

YouLearnedThisYourpromptwilllookdifferentfrommineYoumayhaveyourusernamebeforethe$andthenameofyourcomputerOnWindowsitwillprobablylookdifferenttooThekeyisthatyouseethefollowingpattern

bullTherersquosapromptbullYoutypeacommandthereInthiscaseitrsquospwdbullItprintedsomethingbullRepeat

Youjustlearnedwhatpwddoeswhichmeansldquoprintworkingdirectoryrdquo

WhatrsquosadirectoryItrsquosafolderFolderanddirectoryarethesamethingandtheyrsquoreusedinterchangeablyWhenyouopenyourfilebrowseronyourcomputertographicallyfindfilesyouarewalkingthroughfoldersThosefoldersaretheexactsamethingsastheseldquodirectoriesrdquowersquoregoingtoworkwith

DoMorebullTypepwd20timesandeachtimesayldquoprintworkingdirectoryrdquobullWritedownthepaththatthiscommandgivesyouFinditwithyourgraphicalfilebrowserofchoice

bullNoseriouslytypeit20timesandsayitoutloudSsshJustdoit

IfYouGetLostAsyougothroughtheseinstructionsyoumaygetlostYoumaynotknowwhereyouareorwhereafileisandhavenoideahowtocontinueTosolvethisproblemIamgoingtoteachyouthecommandstotypetostopbeinglostWheneveryougetlostitismostlikelybecauseyouweretypingcommandsandhavenoideawhereyoursquoveendedupWhatyoushoulddoistypepwdtoprintyourcurrentdirectoryThistellsyouwhereyouareThenextthingisyouneedtohaveawayofgettingbacktowhereyouaresafeyourhomeTodothistypecd~andyouarebackinyourhomeThismeansifyougetlostatanytimetype

pwd

cd~

ThefirstcommandpwdtellsyouwhereyouareThesecondcommandcd~takesyouhomesoyoucantryagain

DoThisRightnowfigureoutwhereyouareandthengohomeusingpwdandcd~Thiswillmakesureyouarealwaysintherightplace

YouLearnedThisHowtogetbacktoyourhomeifyouevergetlost

MakeaDirectory(mkdir)Inthisexerciseyoulearnhowtomakeanewdirectory(folder)usingthemkdircommand

DoThis

DoThisRememberYouneedtogohomefirstDoyourpwdthencd~beforedoingthisexerciseBeforeyoudoallexercisesinthisappendixalwaysgohomefirstLinuxmacOS

Clickheretoviewcodeimage

Exercise4Session

$pwd

$cd~

$mkdirtemp

$mkdirtempstuff

$mkdirtempstuffthings

$mkdir-ptempstuffthingsorangeapplepeargrape

$

Windows

Clickheretoviewcodeimage

Exercise4WindowsSession

gtpwd

gtcd~

gtmkdirtemp

DirectoryCUserszed

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMtemp

gtmkdirtempstuff

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMstuff

gtmkdirtempstuffthings

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtmkdirtempstuffthingsorangeapplepeargrape

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gt

ThisistheonlytimeIrsquolllistthepwdandcd~commandsTheyareexpectedintheexerciseseverytimeDothemallthetime

YouLearnedThisNowwegetintotypingmorethanonecommandTheseareallthedifferentwaysyoucanrunmkdirWhatdoesmkdirdoItmakesdirectoriesWhyareyouaskingthatYoushouldbedoingyourindexcardsandgettingyourcommandsmemorizedIfyoudonrsquotknowthatldquomkdirmakesdirectoriesrdquothenkeepworkingtheindexcardsWhatdoesitmeantomakeadirectoryYoumightcalldirectoriesldquofoldersrdquoTheyrsquorethesamethingAllyoudidaboveiscreatedirectoriesinsidedirectoriesinsideofmoredirectoriesThisiscalledaldquopathrdquoanditrsquosawayofsayingldquofirsttempthenstuffthenthingsandthatrsquoswhereIwantitrdquoItrsquosasetofdirectionstothecomputerofwhereyouwanttoputsomethinginthetreeoffolders(directories)thatmakeupyourcomputerrsquosharddisk

WarningInthisappendixIrsquomusingthe(slash)characterforallpathssincetheyworkthesameonallcomputersnowHoweverWindowsuserswillneedtoknowthatyoucanalsousethe(backslash)characterandotherWindowsuserswilltypicallyexpectthatattimes

DoMorebullTheconceptofaldquopathrdquomightconfuseyouatthispointDonrsquotworryWersquolldoalotmorewiththemandthenyoursquollgetit

bullMake20otherdirectoriesinsidethetempdirectoryinvariouslevelsGolookatthemwithagraphicalfilebrowser

bullMakeadirectorywithaspaceinthenamebyputtingquotesarounditmkdirIHaveFun

bullIfthetempdirectoryalreadyexiststhenyoursquollgetanerrorUsecdtochangetoaworkdirectorythatyoucancontrolandtryitthereOnWindowsDesktopisagoodplace

ChangeDirectory(cd)Inthisexerciseyoulearnhowtochangefromonedirectorytoanotherusingthecdcommand

DoThisIrsquomgoingtogiveyoutheinstructionsforthesesessionsonemoretime

bullYoudonottypeinthe$(Unix)orgt(Windows)bullYoutypeinthestuffafterthisthenhitEnterIfIhave$cdtempyoujusttypecdtempandhitEnter

bullTheoutputcomesafteryouhitEnterfollowedbyanother$orgtpromptbullAlwaysgohomefirstDopwdandthencd~soyougobacktoyourstartingpoint

LinuxmacOS

Clickheretoviewcodeimage

Exercise5Session

$cdtemp

$pwd

~temp

$cdstuff

$pwd

~tempstuff

$cdthings

$pwd

~tempstuffthings

$cdorange

$pwd

~tempstuffthingsorange

$cdapple

$pwd

~tempstuffthingsorangeapple

$cdpear

$pwd

~tempstuffthingsorangeapplepear

$cdgrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$cd

$pwd

~tempstuffthingsorangeapple

$cd

$cd

$pwd

~tempstuffthings

$cd

$pwd

~

$cdtempstuffthingsorangeapplepeargrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$pwd

~

$

Windows

Clickheretoviewcodeimage

Exercise5WindowsSession

gtcdtemp

gtpwd

Path

----

CUserszedtemp

gtcdstuff

gtpwd

Path

----

CUserszedtempstuff

gtcdthings

gtpwd

Path

----

CUserszedtempstuffthings

gtcdorange

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcdapple

gtpwd

Path

----

CUserszedtempstuffthingsorangeapple

gtcdpear

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepear

gtcdgrape

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepeargrape

gtcd

gtcd

gtcd

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcd

gtpwd

Path

----

CUserszedtempstuff

gtcd

gtcd

gtcdtempstuffthingsorangeapplepeargrape

gtcd

gtpwd

Path

----

CUserszed

gt

YouLearnedThisYoumadeallthesedirectoriesinthelastexerciseandnowyoursquorejustmovingaroundinsidethemwiththecdcommandInmysessionaboveIalsousepwdtocheckwhereIamsoremembernottotypetheoutputthatpwdprintsForexampleonline3yousee~tempbutthatrsquostheoutputofpwdfromthepromptaboveitDonottypethisinYoushouldalsoseehowIusethetomoveldquouprdquointhetreeandpath

DoMoreAveryimportantpartoflearningtousethecommandlineinterface(CLI)onacomputerwithagraphicaluserinterface(GUI)isfiguringouthowtheyworktogetherWhenIstartedusingcomputerstherewasnoGUIandyoudideverythingwiththeDOSprompt(theCLI)LaterwhencomputersbecamepowerfulenoughthateveryonecouldhavegraphicsitwassimpleformetomatchCLIdirectorieswithGUIwindowsandfoldersMostpeopletodayhoweverhavenocomprehensionoftheCLIpathsanddirectoriesInfactitrsquosverydifficulttoteachittothemandtheonlywaytolearnabouttheconnectionisforyoutoconstantlyworkwiththeCLIuntilonedayitclicksthatthingsyoudointheGUIwillshowupintheCLI

dayitclicksthatthingsyoudointheGUIwillshowupintheCLIThewayyoudothisisbyspendingsometimefindingdirectorieswithyourGUIfilebrowserthengoingtothemwithyourCLIThisiswhatyoursquolldonext

bullcdtotheappledirectorywithonecommandbullcdbacktotempwithonecommandbutnotfurtherabovethatbullFindouthowtocdtoyourldquohomedirectoryrdquowithonecommandbullcdtoyourDocumentsdirectorythenfinditwithyourGUIfilebrowser(FinderWindowsExploreretc)

bullcdtoyourDownloadsdirectorythenfinditwithyourfilebrowserbullFindanotherdirectorywithyourfilebrowserthencdtoitbullRememberwhenyouputquotesaroundadirectorywithspacesinitYoucandothatwithanycommandForexampleifyouhaveadirectoryIHaveFunthenyoucandocdIHaveFun

ListDirectory(ls)Inthisexerciseyoulearnhowtolistthecontentsofadirectorywiththelscommand

DoThisBeforeyoustartmakesureyoucdbacktothedirectoryabovetempIfyouhavenoideawhereyouareusepwdtofigureitoutandthenmovethereLinuxmacOS

Exercise6Session

$cdtemp

$ls

stuff

$cdstuff

$ls

things

$cdthings

$ls

orange

$cdorange

$ls

apple

$cdapple

$ls

pear

$cdpear

$ls

$cdgrape

$ls

$cd

$ls

grape

$cd

$ls

orange

$cd

$ls

stuff

$

Windows

Clickheretoviewcodeimage

Exercise6WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuff

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcdthings

gtls

DirectoryCUserszedtempstuffthings

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMorange

gtcdorange

gtls

DirectoryCUserszedtempstuffthingsorange

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMapple

gtcdapple

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcdpear

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcdgrape

gtls

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gt

YouLearnedThisThelscommandlistsoutthecontentsofthedirectoryyouarecurrentlyinYoucanseemeusecdtochangeintodifferentdirectoriesandthenlistwhatrsquosinthemsoIknowwhichdirectorytogotonextTherearealotofoptionsforthelscommandbutyoursquolllearnhowtogethelponthoselaterwhenwecoverthehelpcommand

DoMore

bullTypeeveryoneofthesecommandsinYouhavetoactuallytypethesetolearnthemJustreadingthemisnotgoodenoughIrsquollstopyellingnow

bullOnUnixtrythels-lRcommandwhileyoursquoreintempbullOnWindowsdothesamethingwithdir-RbullUsecdtogettootherdirectoriesonyourcomputerandthenuselstoseewhatrsquosinthem

bullUpdateyournotebookwithnewquestionsIknowyouprobablyhavesomebecauseIrsquomnotcoveringeverythingaboutthiscommand

bullRememberthatifyougetlostuselsandpwdtofigureoutwhereyouareandthengotowhereyouneedtobewithcd

RemoveDirectory(rmdir)Inthisexerciseyoulearnhowtoremoveanemptydirectory

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise7Session

$cdtemp

$ls

stuff

$cdstuffthingsorangeapplepeargrape

$cd

$rmdirgrape

$cd

$rmdirpear

$cd

$ls

apple

$rmdirapple

$cd

$ls

orange

$rmdirorange

$cd

$ls

things

$rmdirthings

$cd

$ls

stuff

$rmdirstuff

$pwd

~temp

$

WarningIfyoutrytodormdironmacOSanditrefusestoremovethedirectoryeventhoughyouarepositiveitrsquosemptythenthereisactuallyafileintherecalledDS_StoreInthatcasetyperm-rfltdirgtinstead(replaceltdirgtwiththedirectoryname)

Windows

Clickheretoviewcodeimage

Exercise7WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuffthingsorangeapplepeargrape

gtcd

gtrmdirgrape

gtcd

gtrmdirpear

gtcd

gtrmdirapple

gtcd

gtrmdirorange

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMthings

gtrmdirthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMstuff

gtrmdirstuff

gtpwd

Path

----

CUserszedtemp

gtcd

gt

YouLearnedThisIrsquomnowmixingupthecommandssomakesureyoutypethemexactlyandpayattentionEverytimeyoumakeamistakeitrsquosbecauseyouarenrsquotpayingattentionIfyoufindyourselfmakingmanymistakesthentakeabreakorjustquitforthedayYoursquovealwaysgottomorrowtotryagainInthisexampleyoursquolllearnhowtoremoveadirectoryItrsquoseasyYoujustgotothedirectoryrightaboveitthentypermdirltdirgtreplacingltdirgtwiththenameofthedirectorytoremove

DoMorebullMake20moredirectoriesandremovethemallbullMakeasinglepathofdirectoriesthatis10deepandremovethemoneatatimejustlikeIdidpreviously

bullIfyoutrytoremoveadirectorywithcontentsyouwillgetanerrorIrsquollshowyouhowtoremovethoseinlaterexercises

MovingAround(pushdpopd)InthisexerciseyoulearnhowtosaveyourcurrentlocationandgotoanewlocationwithpushdYouthenlearnhowtoreturntothesavedlocationwithpopd

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise8Session

$cdtemp

$mkdirilikeicecream

$pushdilikeicecream

~tempilikeicecream~temp

$popd

~temp

$pwd

~temp

$pushdilike

tempiliketemp

$pwd

~tempilike

$pushdicecream

~tempilikeicecreamtempiliketemp

$pwd

~tempilikeicecream

$popd

tempiliketemp

$pwd

~tempilike

$popd

~temp

$pushdilikeicecream

~tempilikeicecream~temp

$pushd

~temp~tempilikeicecream

$pwd

~temp

$pushd

~tempilikeicecream~temp

$pwd

~tempilikeicecream

$

Windows

Windows

Clickheretoviewcodeimage

Exercise8WindowsSession

gtcdtemp

gtmkdirilikeicecream

DirectoryCUserszedtempilike

ModeLastWriteTimeLengthName

---------------------------

d----122020111105AMicecream

gtpushdilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtemp

gtpushdilike

gtpwd

Path

----

CUserszedtempilike

gtpushdicecream

gtpwd

Path

----

CUserszedtempilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtempilike

gtpopd

gt

WarningInWindowsyounormallydonrsquotneedthe-poptionlikeyoudoinLinuxHoweverIbelievethisisamorerecentdevelopmentsoyoumayrunintoolderWindowsPowerShellversionsthatdorequirethe-pIfyouhavemoreinformationonthispleaseemailmeathelplearncodethehardwayorgsoIcansortoutwhethertomention-pforWindowsornot

YouLearnedThisYoursquoregettingintoprogrammerterritorywiththesecommandsbuttheyrsquoresohandyIhavetoteachthemtoyouThesecommandsletyoutemporarilygotoadifferentdirectoryandthencomebackeasilyswitchingbetweenthetwoThepushdcommandtakesyourcurrentdirectoryandldquopushesrdquoitintoalistforlaterthenitchangestoanotherdirectoryItrsquoslikesayingldquoSavewhereIamthengohererdquoThepopdcommandtakesthelastdirectoryyoupushedandldquopopsrdquoitofftakingyoubackthereFinallyonUnixpushdifyourunitbyitselfwithnoargumentsitwillswitchbetweenyourcurrentdirectoryandthelastoneyoupushedItrsquosaneasywaytoswitchbetweentwodirectoriesThisdoesnotworkinPowerShell

DoMorebullUsethesecommandstomovearounddirectoriesalloveryourcomputerbullRemovetheilikeicecreamdirectoriesandmakeyourownthenmovearoundinthem

bullExplaintoyourselftheoutputthatpushdandpopdwillprintoutforyouNoticehowitworkslikeastack

bullYoualreadyknowthisbutrememberthatmkdir-p(onLinuxmacOS)willmakeanentirepathevenifallthedirectoriesdonrsquotexistThatrsquoswhatIdidfirstforthisexercise

bullRememberthatWindowswillmakeafullpathanddoesnotneedthe-p

MakingEmptyFiles(touchNew-Item)Inthisexerciseyoulearnhowtomakeanemptyfileusingthetouch(New-ItemonWindows)command

DoThisLinuxmacOS

Exercise9Session

$cdtemp

$touchiamcooltxt

$ls

iamcooltxt

$

Windows

Clickheretoviewcodeimage

Exercise9WindowsSession

gtcdtemp

gtNew-Itemiamcooltxt-typefile

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12172011903AMiamcooltxt

gt

YouLearnedThisYoulearnedhowtomakeanemptyfileOnUnixtouchdoesthisanditalsochangesthetimesonthefileIrarelyuseitforanythingotherthanmakingemptyfilesOnWindowsyoudonrsquothavethiscommandsoyoulearnedhowtousetheNew-Itemcommandwhichdoesthesamethingbutcanalsomakenewdirectories

DoMorebullUnixMakeadirectorychangetoitandthenmakeafileinitThenchangeonelevelupandrunthermdircommandinthisdirectoryYoushouldgetanerrorTrytounderstandwhyyougotthiserror

bullWindowsDothesamethingbutyouwonrsquotgetanerrorYoursquollgetapromptaskingifyoureallywanttoremovethedirectory

CopyaFile(cp)Inthisexerciseyoulearnhowtocopyafilefromonelocationtoanotherwiththecpcommand

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise10Session

$cdtemp

$cpiamcooltxtneattxt

$ls

iamcooltxtneattxt

$cpneattxtawesometxt

$ls

awesometxtiamcooltxtneattxt

$cpawesometxtthefourthfiletxt

$ls

awesometxtiamcooltxtneattxtthefourthfiletxt

$mkdirsomething

$cpawesometxtsomething

$ls

awesometxtiamcooltxtneattxtsomethingthefourthfiletxt

$lssomething

awesometxt

$cp-rsomethingnewplace

$lsnewplace

awesometxt

$

Windows

Clickheretoviewcodeimage

Exercise10WindowsSession

gtcdtemp

gtcpiamcooltxtneattxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpneattxtawesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpawesometxtthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtmkdirsomething

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

gtcpawesometxtsomething

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtlssomething

DirectoryCUserszedtempsomething

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtcp-recursesomethingnewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gt

YouLearnedThisNowyoucancopyfilesItrsquossimpletojusttakeafileandcopyittoanewoneInthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectory

InthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectoryIrsquomgoingtotellyouasecretaboutprogrammersandsystemadministratorsnowTheyarelazyIrsquomlazyMyfriendsarelazyThatrsquoswhyweusecomputersWeliketomakecomputersdoboringthingsforusIntheexercisessofaryouhavebeentypingrepetitiveboringcommandssothatyoucanlearnthembutusuallyitrsquosnotlikethisUsuallyifyoufindyourselfdoingsomethingboringandrepetitivetherersquosprobablyaprogrammerwhohasfiguredouthowtomakeiteasierYoujustdonrsquotknowaboutityetTheotherthingaboutprogrammersistheyarenrsquotnearlyascleverasyouthinkIfyouoverthinkwhattotypethenyoursquollprobablygetitwrongInsteadtrytoimaginewhatthenameofacommandistoyouandtryitChancesarethatitrsquosanameorsomeabbreviationsimilartowhatyouthoughtitwasIfyoustillcanrsquotfigureitoutintuitivelythenaskaroundandsearchonlineHopefullyitrsquosnotsomethingreallystupidlikeROBOCOPY

DoMorebullUsethecp-rcommandtocopymoredirectorieswithfilesinthembullCopyafiletoyourhomedirectoryordesktopbullFindthesefilesinyourGUIandopentheminatexteditorbullNoticehowsometimesIputa(slash)attheendofadirectoryThatmakessurethefileisreallyadirectorysoifthedirectorydoesnrsquotexistIrsquollgetanerror

MovingaFile(mv)Inthisexerciseyoulearnhowtomoveafilefromonelocationtoanotherusingthemvcommand

DoThisLinuxmacOS

Exercise11Session

$cdtemp

$mvawesometxtuncooltxt

$ls

newplaceuncooltxt

$mvnewplaceoldplace

$ls

oldplaceuncooltxt

$mvoldplacenewplace

$ls

newplaceuncooltxt

$

Windows

Clickheretoviewcodeimage

Exercise11WindowsSession

gtcdtemp

gtmvawesometxtuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvnewplaceoldplace

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMoldplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvoldplacenewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gt

YouLearnedThisMovingfilesorratherrenamingthemItrsquoseasygivetheoldnameandthenewname

DoMoreMoveafileinthenewplacedirectorytoanotherdirectorythenmoveitback

ViewaFile(lessmore)TodothisexerciseyoursquoregoingtodosomeworkusingthecommandsyouknowsofarYoursquollalsoneedatexteditorthatcanmakeplaintext(txt)filesHerersquoswhatyoudo

bullOpenyourtexteditorandtypesomestuffintoanewfileOnmacOSthiscouldbeTextWranglerOnWindowsthismightbeNotepad++OnLinuxthiscouldbegeditAnyeditorwillwork

bullSavethatfiletoyourdesktopandnameittesttxtbullInyourshellusethecommandsyouknowtocopythisfiletoyourtempdirectorythatyoursquovebeenworkingwith

Onceyoursquovedonethatcompletethisexercise

Onceyoursquovedonethatcompletethisexercise

DoThisLinuxmacOS

Exercise12Session

$lesstesttxt

[displaysfilehere]

$

ThatrsquositTogetoutoflessjusttypeq(asinquit)Windows

Exercise12WindowsSession

gtmoretesttxt

[displaysfilehere]

gt

WarningIntheprecedingoutputIrsquomshowing[displaysfilehere]toldquoabbreviaterdquowhatthatprogramshowsIrsquolldothiswhenImeantosayldquoShowingyoutheoutputofthisprogramistoocomplexsojustinsertwhatyouseeonyourcomputerhereandpretendIdidshowittoyourdquoYourscreenwillnotactuallyshowthis

YouLearnedThisThisisonewaytolookatthecontentsofafileItrsquosusefulbecauseifthefilehasmanylinesitwillldquopagerdquosothatonlyonescreenfulatatimeisvisibleIntheDoMoresectionyoursquollplaywiththissomemore

DoMorebullOpenyourtextfileagainandrepeatedlycopy-pastethetextsothatitrsquosabout50ndash100lineslong

bullCopyittoyourtempdirectoryagainsoyoucanlookatitbullNowdotheexerciseagainbutthistimepagethroughitOnUnixyouuse

thespacebarandw(theletterw)togodownandupArrowkeysalsoworkOnWindowsjusthitthespacebartopagethrough

bullLookatsomeoftheemptyfilesyoucreatedtoobullThecpcommandwilloverwritefilesthatalreadyexistsobecarefulcopyingfilesaround

StreamaFile(cat)YoursquoregoingtodosomemoresetupforthisonesoyougetusedtomakingfilesinoneprogramandthenaccessingthemfromthecommandlineWiththesametexteditorfromthelastexercisecreateanotherfilenamedtest2txtbutthistimesaveitdirectlytoyourtempdirectory

DoThisLinuxmacOS

Exercise13Session

$lesstest2txt

[displaysfilehere]

$cattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

$cattesttxt

Hitherethisiscool

$

Windows

Exercise13WindowsSession

gtmoretest2txt

[displaysfilehere]

gtcattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

gtcattesttxt

Hitherethisiscool

gt

RememberthatwhenIsay[displaysfilehere]IrsquomabbreviatingtheoutputofthatcommandsoIdonrsquothavetoshowyouexactlyeverything

YouLearnedThisDoyoulikemypoemTotallygoingtowinaNobelAnywayyoualreadyknowthefirstcommandandIrsquomjusthavingyoucheckthatyourfileisthereThenyoucatthefiletothescreenThiscommandjustspewsthewholefiletothescreenwithnopagingorstoppingTodemonstratethatIhaveyoudothistotesttxtwhichshouldjustspewabunchoflinesfromthatexercise

DoMorebullMakeafewmoretextfilesandworkwithcatbullUnixTrycattesttxttest2txtandseewhatitdoesbullWindowsTrycattesttxttest2txtandseewhatitdoes

RemovingaFile(rm)Inthisexerciseyoulearnhowtoremove(delete)afileusingthermcommand

DoThisLinux

Clickheretoviewcodeimage

Exercise14Session

$cdtemp

$ls

uncooltxtiamcooltxtneattxtsomethingthefourthfiletxt

$rmuncooltxt

$ls

iamcooltxtneattxtsomethingthefourthfiletxt

$rmiamcooltxtneattxtthefourthfiletxt

$ls

something

$cp-rsomethingnewplace

$

$rmsomethingawesometxt

$rmdirsomething

$rm-rfnewplace

$ls

$

Windows

Clickheretoviewcodeimage

Exercise14WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtrmuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtrmiamcooltxt

gtrmneattxt

gtrmthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

gtcp-rsomethingnewplace

gtrmsomethingawesometxt

gtrmdirsomething

gtrm-rnewplace

gtls

gt

YouLearnedThisHerewecleanupthefilesfromthelastexerciseRememberwhenIhadyoutrytormdironadirectorywithsomethinginitWellthatfailedbecauseyoucanrsquotremoveadirectorywithfilesinitTodothatyouhavetoremovethefileorrecursivelydeleteallofitscontentsThatrsquoswhatyoudidattheendofthis

DoMorebullCleanupeverythingintempfromalltheexercisessofarbullWriteinyournotebooktobecarefulwhenrunningrecursiveremoveonfiles

ExitingYourTerminal(exit)DoThisLinuxmacOS

Exercise23Session

$exit

Windows

Exercise23WindowsSession

gtexit

YouLearnedThisYourfinalexerciseishowtoexitaTerminalAgainthisisveryeasybutIrsquomgoingtohaveyoudomore

DoMore

ForyourlastsetofexercisesIrsquomgoingtohaveyouusethehelpsystemtolookupasetofcommandsyoushouldresearchandlearnhowtouseonyourownHerersquosthelistforUnix

bullxargsbullsudobullchmodbullchown

ForWindowslookupthesethingsbullforfilesbullrunasbullattribbullicacls

Findoutwhattheseareplaywiththemandthenaddthemtoyourindexcards

CommandLineNextStepsYouhavecompletedthecrashcourseAtthispointyoushouldbeabarelycapableshelluserTherersquosawholehugelistoftricksandkeysequencesyoudonrsquotknowyetandIrsquomgoingtogiveyouafewfinalplacestogoresearchmore

UnixBashReferencesTheshellyoursquovebeenusingiscalledBashItrsquosnotthegreatestshellbutitrsquoseverywhereandhasalotoffeaturessoitrsquosagoodstartHerersquosashortlistoflinksaboutBashyoushouldgoread

BashCheatSheethttpslearncodethehardwayorgunixbash_cheat_sheetpdf(createdbyRaphaelandCClicensed)

ReferenceManualhttpwwwgnuorgsoftwarebashmanualbashrefhtml

PowerShellReferencesOnWindowstherersquosreallyonlyPowerShellHerersquosalistofusefullinksforyourelatedtoPowerShell

OwnerrsquosManualhttptechnetmicrosoftcomen-uslibraryee221100aspx

CheatSheethttpsdownloadmicrosoftcomdownload2122122F0B9-0EE6-4E6D-BFD6-F9DCD27C07F9WS12_QuickRef_Download_FilesPowerShell_LangRef_v3pdf

MasterPowerShellhttppowershellcomcsblogsebookdefaultaspx

Index

Symbols(colon)creatingfunctions61ndash62(dot)operator146ndash148193(double-quotes)avoidusingwithTrueFalse31createstrings26ndash27createstringswithsingle-quotesvs29escapinginsidestrings34ndash36promptandpass47

gt=(greater-than-equal)operator16ndash1797+=(incrementby)operator69ndash70105lt=(less-than-equal)operator16ndash1797-(minus)operator16ndash17=(notequal)operator97ndash98100ndash102(single-quotes)createstrings26ndash27createstringswithdouble-quotesvs29escapinginsidestrings34ndash36indicatingstrings57

(triple-single-quotes)36(triple-quotes)dedentfunction170ndash175errorswhenputtingspacesbetween33escapinginsidestrings3436

(slash)character16ndash17257(backslash)character33ndash34257(doublebacklash)character36_(underscore)character20ndash2162189+(plus)operator16ndash1754==(equal)operatorfunctionof21

practicingBooleanlogic100ndash102intruthtables98astruthterm97

=(single-equal)operator21(poundoroctothorpe)character1214ndash1517(percent)operator1617ndash18(asterisk)operator16ndash17[]leftandrightbracketslists112ndash114^(caret)characterviewoutput11charactersembeddedvariablesinstrings24ndash25lt(lessthan)operator16ndash17ltgt=(notequal)vs102gt(greaterthan)operator16ndash1791

AactivatescriptPowershell195Addressesweb225altered()functioninheritance180ndash183Alternativetexteditors6ndash7and

inBooleanlogic100ndash102astruthterm96ndash98

apppy

buildfirstwebsite217ndash221creategameengine239ndash241createHTMLforms228ndash229howformswork226ndash227writeautomatedtestsforforms231ndash232

app_testspyfile231241aproposcommand252args60ndash62Argumentscreatingfunctions6266argv

asargumentvariable42

promptingandpassingusing46ndash47readingandwritingfiles54readingfiles48ndash50unpacking42ndash44usinginput()vs44

Arrayslistsvs114ASCII(AmericanStandardCodeforInformationInterchange)80ndash81assert_equal()functionautomatedtesting201ndash203assert_raises()functionwritingtestexpectedtofail215asterisk()operator16ndash17Atomtexteditoralternativesto6ndash7Linuxsetup4ndash5macOSsetup2Windowssetup3ndash4workingwithfirstprogram9

Automatedtestsforforms232improving242overviewof200ndash203refactoringgothonwebgameusing238ndash239testfirstwith206ndash207

BBackslash()character33ndash34257Bashreferences283Big5encoding85bindirectoryskeletonprojectdirectory198Bits8182Blocksofcode106ndash110Booleanlogicmemorizingvslearning98practicing100ndash102rulesforif-statements126

Bottomupprocessesvstopdown169Brackets([])lists112ndash114Branchesandfunctions122ndash124Breakingfiles8592232Browsercreateenginetorungamein234ndash241gettinginputfromSeeInputgettingfrombrowserhowitaccessesinformation225ndash226

Bytesbreakingfiles85conventionsforencoding80ndash81defined78dissectingcode82ndash84dissectingoutput82

CC3algorithmsuper()function183Cardinalnumberslists120ndash121137caret(^)characterviewoutput11catcommandprintwholefile57252278ndash279cdcommandchangedirectorymacOSLinux251overviewof258ndash260Windows252

cd~command255CharactersencodingSeeStringsbytesandcharacterencodingsimportanceoflearningnamesof76fortruthterms96ndash97

Checklistcreatingfunction62ChildclassesSeeInheritancevscompositionClassesaddsconsistencytoprogram146asblueprintsfornewmini-modules149codeandtestinOOP167ndash169

designhierarchyinOOP166ndash167inheritancevscompositionSeeInheritancevscompositionobject-orientedphrasedrill152ndash153object-orientedreadingtest154ndash155object-orientedworddrill152researchingPython137similaritytomodules147ndash148styling189astemplatesmintingnewobjects186

CLI(commandlineinterface)usingonGUI261closecommandclosefile52ndash53Codeavoidhardcodingfilenames48blocksof106ndash107classestesting167ndash169createonelineof57findingerrorsin132inheritancevscompositionforreusable185OOPanalysisanddesign170ndash176parser211ndash214practicingEnglishto155reading132readingbackwardSeeReadingcodebackwardreadingphrases156refactoringforgothonwebgame234ndash239researchingpieceof78styling190testingotherprogrammerrsquos94typingintoTerminalPowerShell50

Colon()creatingfunctions61ndash62Colorsintexteditors12Command-linecrashcoursechangedirectory(cd)258ndash261copyfile(cp)272ndash275

exityourterminal(exit)282howtouseappendix248ndash249introduction248listdirectory(ls)261ndash265makedirectory(mkdir)255ndash257makeemptyfiles(touchNew-Item)271ndash272memorizingthings249movearound(pushdpopd)268ndash271movefile(mv)275ndash276pathsfoldersdirectories(pwd)253ndash255PowerShellreferences283removedirectory(rmdir)265ndash268removefile(rm)280ndash281setup249ndash253streamfile(cat)278ndash279UnixBashreferences283viewfile(lessmore)277ndash278

Commandlineinterface(CLI)usingonGUI261Commandsconvertingargumentstostrings44asfunctionsandmethods50learning44

Commentsaddingwhenreadingcode132creatingfunctionswith65ndash66designingdebuggingwith127functionsfileswith69gettinghelpwithdocumentation92is-ahas-arelationshipsusing159ndash160readingwritingfilesusing53usinginPython14ndash15variablenames21writinggood190writingwhenyoudonotunderstandcode29124

Composition

Compositiondefined152overviewof184ndash185whentouseinheritanceor185

Connectionsweb225ndash226Conventionsforencodingtext80ndash81Copyingfileswritingscriptfor56ndash58cpcopyfileordirectorymacOSLinux251overviewof272ndash275Windows252

curlcommandgeneraterequesttypes232

DDatastructuresdictionariesas140ndash144listsascommon136ndash137

Datatypeslistof129DBES(DecodeBytesEncodeStrings)dissectingcode83ndash84Debuggingdesigningand126ndash127fixingerrorsinfirstwebsite219refactoredcode241

Decisionsmaking108ndash110dedent()function-stylestrings170ndash175def(createfunction)branchesandfunctions122ndash124creategameengine239ndash241defined152filesworkingwithfunctions68ndash70functionscanreturnsomething72ndash74functionsworkingwithvariables90ndash93is-ahas-arelationships159ndash160overviewof60ndash62inreadingtest154ndash155

delkeyworddeletefromdictionary141Designinganddebugging126ndash127dict

howformswork227understandingdictionaries140ndash144

Dictionariesexampleof141ndash143functionsof143ndash144listsvs140ndash141modulessimilarto146ndash147storescenesbynamein175

diefunctionif-statementrules126dir-rfindfilesinWindows253DirectoriescausesofImportErrors209ldquoHelloWorldrdquowebapplication217LinuxmacOScommand-linefor251skeletonprojectSeeSkeletonprojectdirectoryWindowscommand-linefor252

DjangoTutorial244Documentationcheckoutprojectsbuildsomethingusing244gettinghelpwithcomments92writinggoodcomments190

Dot()operator146ndash148193Doublebacklash()36Double-quotesSee(double-quotes)

Eechoprintsomearguments252253Elementsaccessinglist120ndash121elif

branchesandfunctions122ndash124andelse107makingdecisions108ndash110

else

branchesandfunctions122ndash124andif-statement106ndash107makingdecisions108ndash110rulesforif-statements126

Encodingsbytescharacter80ndash85envcommandlookatyourenvironment252EqualoperatorSee==(equal)operatorErrormessagesbuildingfirstwebsite218ndash219EOFError155ImportErrorSeeImportErrorsNameError47ParserError211ndash214printing29forspacesbetweentriple-quotes33forspellingmistakes33ValueErrorSeeValueErrorsvariablenames21viewingoutputinfirstprogram11whenmakingscriptshorter58

Escapesequencesfordifferentcharactersinstrings34ndash35practicing87readingandwritingfiles54reviewing130supportedbyPython35

exceptkeywordexceptions206Exceptionshowtoraise211ndash214andnumbers206

existscommandcopyingfiles56ndash58exitcommandexitshell124252282exportcommandexportnewenvironmentvariable252

F

Ffcharacterembeddingvariablesinsidestrings24ndash25promptingandpassing46ndash47inreadline()70usingwithfunctions69

Falsekeywordavoidquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98

Featuresaddingtoscript42alsocalledmodules42ndash43

FileTransferProtocol(FTP)andURLs225Filenames48ndash50Filescopying56ndash58creating50andfunctions68ndash70LinuxmacOScommand-linefor251ndash252reading48ndash50readingandwriting52ndash54Windowscommand-linefor252ndash253

findcommandfiles252Firstprogramcreate8ndash12flaskframeworkcreatebasictemplatesforwebsite219ndash221creategameengine239ndash241fixerrors218ndash219ImportErrorafterinstalling222installingforfirstwebsite216makeldquoHelloWorldrdquowebapplication216ndash217testingtricksforcreatingfakesessions242webpyvs221

whatisgoingon218FLASK_DEBUGnotsafetoactivateonInternet219Flowcharts132FoldersSeeDirectoriesfooOOP152for-loops

buildinglistswith112ndash114rulesfor126whentouselists137while-loopsvs118

forOOP154ndash155forfiles253formatfunction30ndash31Formatstringsformatterformat()30oldstyle130ndash131overviewof24ndash25readingandwritingfiles54

format()syntaxformattingstrings26ndash2730Formsautomatedtestsfor232creatingHTML227ndash229howtheywork226ndash227

FTP(FileTransferProtocol)andURLs225Functionsaccessinginmodulewith(dot)operator146ndash147alsocalledmethodscommands50branchesand122ndash124canreturnsomething72ndash74createchecklistfor62andfiles68ndash70overviewof60ndash62practicing87ndash8890ndash93readingcode132

replicatingimplicitinheritance184ndash185styling189usingprintvsreturnin93andvariables64ndash6687ndash88viewingcalls137

GGamestartofyourwebcreatingengine239ndash241overviewof234refactoring234ndash239yourfinalexam241ndash242

GamesanalysisanddesignSeeObject-orientedanalysisanddesignmakingyour188ndash191

gothonwebprojectanalysisofsimplegameengine165ndash169codefor170ndash176creatinglayouttemplate234ndash239makingintofirstwebapplication217ndash221refactoringcodecreatingwebenginetorun234ndash241

Grammarmakingsentences211215Greater-than-equal(gt=)operator16ndash1797Greaterthan(gt)operator16ndash1791grepcommandfindthingsinsidefiles252GUI(graphicaluserinterface)usingCLIon261

HHardcodedfilenamesavoid48has-arelationships152158ndash162ldquoHelloWorldrdquowebapplicationcreatebasictemplates219ndash221fixingerrors218ndash219

Helpcreatesystemfor242

gettingmodule92helpcommandWindows253helpctrcommandWindows253Hierarchyclass166ndash169hostname

mycomputerrsquosnetworkname251252understandURLs225

HTMLcreatebasictemplatesforwebsite219ndash221createforms227ndash229creategameengine239ndash241improveappearanceof242research232understandresponse226

HTTPrequests218244researchHTTPREC232understandURLs225

IIDLEavoidusing1231if-elsetry-exceptvs209if-statements

branchesandfunctions122ndash124elseand106ndash107loopsandlists112ndash114makedecisions83ndash84108ndash110overviewof104ndash105readcode132rulesfor126

Implicitinheritancecombinewithothertypesofinheritance182compositionvs184ndash185overviewof178ndash179

import

addfeaturestoscript42copyfiles56ndash58filewithmodules146makeagameyourself188objectsassimilarto148ndash149

ImportErrorsafterinstallingflask222causesof209242createskeletonprojectdirectory199

Incrementby(+=)operator69ndash70105Indentation61ndash62106index()

creategameengine239ndash241createHTMLforms229howformswork227

indexGEThandler224Inheritanceavoidmultiple178183185object-orientedphrasedrill152object-orientedreadingtest154ndash155object-orientedworddrill152

Inheritancevscompositionalterbehaviorbeforeorafter180ndash181implicitinheritance179overrideexplicitly180overviewof178reasonforsuper()183threekindsofinheritancecombined182ndash183understandcomposition184ndash185understandinheritance178ndash179usinginheritancevscomposition185usingsuper()with__init__()183

__init__functioninitializingnewlycreatedemptyobject149

inis-ahas-arelationships159ndash162runningreliablyforparentclass162tryingnottodotoomuchin189usingselfwhenmakingfunctionsforclasses151usingsuper()in183

input()

askingquestions38ndash39enteringownvalues74parameterto(gt)124parametersunpackingvariables42ndash44promptingandpassing46ndash47promptingpeople40ndash41readingfiles48ndash50

Inputadvanceduserourgamelexicon204ndash206overviewof204testfirstchallenge206ndash207whatyoushouldtest207ndash209

Inputgettingfrombrowserbreakingit232creatingHTMLforms227ndash229creatinglayouttemplate229ndash230howformswork226ndash227howwebworks224ndash226writingautomatedtestsforforms232

ltinputgttags229ndash230Instance152ndash153Instantiation148ndash149Internetflaskdebuggermodenotsafeon219Internetresearchcheckoutprojectstrytobuildsomething244findthings5ndash6functionsandfiles69importstatement57

object-orientedprogramming137151pydoc40ndash41readingfiles49

int()functionconvertingcommandlineargumentstrings44IPaddressesandURLs225is-arelationships152158ndash162

JJinja2Documentationtemplatelanguage221

KKeywordslistof128ndash129Kivy244

LLayouttemplatecreate232LearnCTheHardWay244LearnRubyTheHardWay244len()function5658lesscommandviewfileinmacOSLinux252277ndash278Less-than-equal(lt=)operator16ndash1797Lessthan(lt)operator16ndash17LexiconcreatinggamemakesentencesSeeSentencesmakingoverviewof204ndash206testfirstchallenge206ndash207whatyoushouldtest207ndash209

Librariesdefined43LinuxmacOSalternativetexteditorsfor7getterminalopenandworking250ndash251projectskeletonsetup192ndash194setupexercise4ndash5

LinuxmacOScommand-linecatstreamfile278ndash279

cdchangedirectory258ndash259261cpcopyfileordirectory272274ndash275exitexitshell282lessviewfile277ndash278listofcommands251ndash252lslistdirectory262265mkdirmakedirectory256ndash257mvmovefileordirectory275277pushdpopd(movedirectory)268ndash271pwdprintworkingdirectory253ndash255rmstreamfile278ndash279rmdirremovedirectory266268

Listsaccesselementsof120ndash121buildusingfor-loops112ndash114doingthingsto134ndash138making2-D114processinglistsofthings78whentouse137

localhost

buildfirstwebsite218221webconnection225

Logicmemorizing96ndash98practicingBoolean100ndash102

Loginresearchingwebapplication242Lookuptablesdictionariesas144Loopsandlists112ndash114for-loopsSeefor-loopsmakinginfinite124rulesfor126ndash127while-loopsSeewhile-loops

lpthwvirtualenvironmentskeletonproject193195

lslistdirectorymacOSLinux251overviewof261ndash265Windows252

MmacOSSeeLinuxmacOSmainfunctiondissectingcode83manreadmanualpageinmacOSLinux252Mapclassgothonwebprojectcode171storingscenesbynameindictionary175

Mapsanalysisofsimplegameengine165completinggame242withdictionaries143ndash144

matchfunctionparsercode212Math16ndash1839Memorizationofcommandsusingindexcards251ndash253learningcommandline249oflogic96ndash98tipsfor96

Methodresolutionorder(MRO)super()183Methodsalsocalledfunctionsandcommands50functionsvs189

Minus(--)operator16ndash17mkdirmakedirectorymacOSLinux251overviewof255ndash257Windows252

Modifiersreadingandwritingfiles54ModulescausesofImportErrors209

gettinghelpfor92overviewof146ndash147replicatingimplicitinheritancein184ndash185usingclassesvs147ndash148

morecommandviewfileinWindows252278MRO(methodresolutionorder)super()183Multipleinheritanceavoid178183185mvcommandmovefileordirectorymacOSLinux251overviewof275ndash277Windows252

NNameErrormessage47Namescreatingfunction62189definemodules42ndash43filenames48ndash50importanceoflearningsymbol76variable20ndash2260ndash62

NaturalLanguageToolKit244Nestedstructureslistsas112rulesforif-statements126

new-itemcommandcreateemptyfilesinWindows271ndash272Noneforsomefunctions93nosetestscommandautomatedtests201ndash203automatedtestsforforms231createskeletonprojectdirectory197ndash199syntaxerror203

not

inBooleanlogic100ndash102intruthtables97ndash98

astruthterm97Notequal(=)operator97ndash98100ndash102Nounsobject-orientedprogramming164ndash167Numbersaccesselementsoflists120ndash121exceptionsand206indexlistsinto140ndash141inputtodomath39andmath16ndash18betweenrangeofnumbers110roundingfloatingpoint25

OObject-orientedanalysisanddesignSeealsoGamestartofyourwebanalysisofsimplegameengine165codeclassesandtesttorunthem167ndash169codeforldquoGothonsfromPlanetPercal25rdquo170ndash176createclasshierarchyobjectmapforconcepts166ndash167extractresearchkeyconcepts166overviewof164ndash165repeatandrefine169topdownvsbottomup169whatyoushouldsee176writeordrawaboutproblem165

Object-orientedprogramming(OOP)inheritancevscompositionSeeInheritancevscompositionPythonas146research137151speak152ndash156

Objectsclassesastemplatesthatmintnew186makesentenceswith210ndash211object-orientedphrasedrill152ndash153object-orientedworddrill152parsercode212ndash215

similartoimport148ndash149Octothorpe()character1214ndash1517opencommandreadingandwritingfiles52ndash54OperatorsfindingmorePythonequality102listof131ndash132math16ndash17variablename20ndash22

or

inBooleanlogic100ndash102intruthtables97ndash98astruthterm96

Ordermaintainwithlists137Ordinalnumberslists120ndash121Outputoffirstprogram10ndash11ldquoHelloWorldrdquowebapplication217

override()functioninheritance189

PPandas244Paragraphsif-statementrules126Parametersreadingandwritingfiles54ParentclassesSeeInheritancevscompositionParsercode211ndash214playingwith214ndash215

ParserErrorexception211ndash214Passingpromptingand46ndash47PEMDASacronymorderofmathoperations18Percent()operator1617ndash18Phrasedrillsobject-oriented152ndash156pip36(orjustpip)createskeletonprojectdirectory192ndash195198ndash199installflasktobuildfirstwebsite216

planispherepyfile234ndash238

planisphere_testspyfile238ndash239Plus(+)operator16ndash1754popdcommandpopdirectorymacOSLinux251overviewof268ndash271Windows252

Portswebconnections225POSTautomatedtestsforforms231creatingHTMLforms227ndash229

Pound()character1214ndash1517PowerShellcreategameengine240infirstprogram11ndash12references283typingcodeinto50Windows10setupfor3ndash4195250ndash251

print

debugwith127readcodeusing132whenfunctionsusereturnvs93

Printstringswithmorecomplicatedformatting30ndash31moreexercisesin28ndash2932ndash33usingescapesequences34ndash36variables24ndash25

print_a_linepassincurrentlinenumber68ndash69print_linefunctiondissectingcode83ndash84print_twofunctioncreatefunctions60ndash61Programminglanguagesadvicefromoldprogrammer246ndash247checkoutprojectstrytobuildsomething244howtolearnnew245learningcommandlineSeeCommand-linecrashcourse

Projectskeleton192ndash194Promptsidentifyinappendixexercises254andpassing46ndash47people40ndash41

Prototypelanguages186Pseudocodetestfirstusing207pushdcommandpushdirectorymacOSLinux251overviewof268ndash271Windows252

pwdcommandprintworkingdirectorymacOSLinux251overviewof253ndash255Windows252

pyfilespassingvariablestoscript42ndash44pydoccommandpromptpeople40ndash41PyGame244PYTHONPATHenvironmentvariable240

Qquit()functionreloadPythonafter92

Rraisekeywordexceptions211213ndash214range()functionloops114Rawbytes7982ndash84readcommandreadcontentsoffile52ndash54Readingcode132codeoutloud190files48ndash50andwritingfiles52ndash54

Readingcodebackwardcommentsandpoundcharacters14

defined88printing29reasonsfor15understandinghowto22

readline()function52ndash53687083Refactoringcode234ndash239render_template()function220ndash221requestargsforms227Requestswebgeneratingtypesofwithcurl232learnclientsideofHTTP244process224ndash225understand225

Responsesweb226return

functions72ndash74object-orientedreadingtest155whenfunctionsuseprintvs93

rmstreamfile280ndash281rmdircommandremovedirectorymacOSLinux251overviewof265ndash268Windows252

Roomclassautomatedtests201ndash203creategameengine239ndash241refactorcodeforgothonwebgame234ndash239

round()functionfloatingpointnumbers25Rulesforif-statements126forloops126ndash127whentouseinheritanceorcomposition185

runascommanddangerinwindows252

S

Scanninginputlexicontuples205209Scenes(rooms)analysisofsimplegameengine165ndash167codeclassesforsimplegame167ndash169gothonwebprojectcode170ndash176makinggameyourself188ndash191whatyoushouldsee176

SciPy244ScraPy244Scriptslinkingfunctionsto61makingdecisions107passingvariablesto42ndash44

SearchenginesfindingthingsonInternet5ndash6howtotype(octothorp)character15

seek()functiondefined52ndash53doesnotsetcurrentlineto070researchforfile69

select-stringcommandfindthingsinsideWindowsfiles253self

__init__function148151is-ahas-arelationshipsand159ndash160object-orientedlanguage152ndash155

Sentencesmakingbreakingup205exceptions211grammar211matchandpeek210ndash211overviewof210parsercode211ndash215whatyoushouldtest215

Servershowbrowsersaccessinformationon226

setcommandexportsetnewenvironmentvariableinWindows253Setupexercisealternativetexteditors6ndash7findingthingsonInternet5ndash6Linux4ndash5macOS2ndash3overviewof2warningsforbeginners6Windows3ndash4

setuppyfileskeletonprojectdirectory196198ndash199Single-equal(=)operator21Single-quotesSee(single-quotes)Skeletonprojectdirectoryautomatedtesting200ndash203creatingdirectorystructure195ndash197macOSLinuxsetup192ndash194overviewof192requiredquiz198testingsetup197ndash198using198Windows10setup194ndash195

skipkeywordparsercode213Slash()character16ndash17257Spaceaddingaroundoperatorsforeasierreading22makecodereadablewithvertical190

Spellingmistakeserrormessagesfor33Stopwordsparsercode213Stringsacrossmultiplelines34ndash36complicatedformattingof30ndash31convertcommandlineargumentsto44decodebytesandencode83ndash84embedvariablesinside24ndash25

exerciseinprinting28ndash29listofescapesequencesfor130listofoldstyleformatsfor130ndash131listsmixedwith135ndash136poundcharactersin15readwritefilesin54startnewlinein33andtext26ndash27understanding26asUTF-8encodedsequenceofcharacters82

Stringsbytesandcharacterencodingsbreakingit85dissectcode82ndash84dissectoutput82encodingsdeepdive84ndash85initialresearch78ndash80overviewof78switchesandconventions80ndash81

Stylingcode190functionsandclasses189

Subjectparsercode212ndash215ofsentences210ndash211

sudocommand252super()functioninheritance180ndash183Switches80ndash81Symbolsdatatypes129escapesequencesforstrings130keywords128ndash129learningnamesof76oldstylestringformats130ndash131operators131ndash132readingcode132

SyntaxErrormessageEOL58invalidsyntax1293promptingandpassing47pydoc41viewingoutputinfirstprogram11

Systemsitepackagessetupforskeletonproject193

TTablesdictionariesaslookup144truth97ndash98

Templatescreatebasic219ndash221creategameengine239ndash241createHTMLforms229createlayout229ndash230

templatesindexhtmlfile219ndash221229ndash230templateslayouthtmlfile230TensorFlow244Terminalgettingopenandworking250ndash251Linuxsetup5macOSsetup2ndash3typingcodeinto50whatyoushouldseeinfirstprogram9ndash11Windowssetup3ndash4

Terminologytruth96ndash97webapplication225ndash226

Testcasewriting200ndash201Testfirstprogrammingtactic206ndash207Test_directionstestcase207ndash209TestsSeealsoAutomatedtestsBooleanlogic100ndash102

codeforclassesinOOP168ndash169object-orientedreading153ndash155otherprogrammerrsquoscode94session-basedgameengine241skeletonprojectdirectorysetup197ndash198tricksforcreatingfakesessionsinside242

testsapp_testspy231Testtxtfilecopyingfiles56ndash58Textreadingfiles48ndash50andstrings26ndash27

Texteditorsalternative6ndash7gettingcolorsin12Linuxsetup4ndash5macOSsetup2

Thingsgettingthingsfrom149ndash150TopdownprocessOOPdesign164vsbottomup169

touchcommandmakeemptyfilesinmacOSLinux271ndash272Tracingvariablesreadingcode132Triple-quotes()See(triple-quotes)Triple-single-quotes()36Truekeywordavoidputtingquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98astruthterm97

truncatecommand52ndash54Truthtables97ndash98terms96ndash97

try-exceptif-elsevs209

trykeywordexceptions206Tupleslexicon205typecommandprintwholefileinWindows252

UUnderscore(_)character20ndash2162189Unicode81URLs(UniformResourceLocators)buildfirstwebsite218createHTMLforms228howformswork227overviewof225

UserinputSeeInputadvanceduserUserWarningwhenrunningnosetests203UTF-16standard84ndash85UTF-8standardcomparingUTF-16UTF-32to84ndash85dissectingoutput82encodingtextinPython81fixingterminalunabletodisplay79stringsinPython82ndash84

VValueErrorsandnumbers206parametersunpackingvariables44promptingpassing47

Variablesaccessinmodule146ndash147avoidmoduleorglobal189andfunctions64ndash66for-loopusingundefined114andnames20ndash22andnamescodefunctions60ndash62passingtoscript42ndash44

practicing90ndash93printing24ndash25promptingandpassing46ndash47readingcode132temporarilyinsidefunctions87ndash88writingstringswithtext26ndash27

venvsdirectoryskeletonprojectsetup193ndash195VerbsanalyzeclasshierarchyinOOP165extractkeyconceptsinOOP164makesentenceswith210ndash211parsercode212ndash215

virtualenv192ndash193194

WWarningsforbeginners5ndash6setup2

Webbreakingapplications232howitworks224ndash226learnclientsideof244startofyourgameSeeGamestartofyourweb

Websiteyourfirstcreatebasictemplates219ndash221fixingerrors218ndash219installflaskframework216makeldquoHelloWorldrdquowebapplication216ndash217whatisgoingon218

while-loops

overviewof116ndash118readingcode132rules126whentobreakruleaboutnotusing138

whileTruemakeinfiniteloop124Windows

Windowsalternativetexteditorsfor7setupexercise3ndash4skeletonprojectdirectorysetup194ndash195

Windowscommand-linecatstreamfile259ndash261278ndash279cpcopyfileordirectory272ndash275exitexitshell282gettingPowerShellopenandworkingfor250ndash251listofcommands252ndash253lslistdirectory262ndash265macOSsetup2moreviewfile278mvmovefileordirectory275ndash277pushdpopd(movedirectory)269ndash271pwdprintworkingdirectory254ndash255rmstreamfile278ndash279rmdirremovedirectory266ndash268

Worddrillsobject-oriented152ndash155wordspopfunction93Writeformulasusingfunctions74andreadfiles52ndash54

Xxargscommandexecutearguments252

CodeSnippets

ManytitlesincludeprogrammingcodeorconfigurationexamplesTooptimizethepresentationoftheseelementsviewtheeBookinsingle-columnlandscapemodeandadjustthefontsizetothesmallestsettingInadditiontopresentingcodeandconfigurationsinthereflowabletextformatwehaveincludedimagesofthecodethatmimicthepresentationfoundintheprintbookthereforewherethereflowableformatmaycompromisethepresentationofthecodelistingyouwillseealdquoClickheretoviewcodeimagerdquolinkClickthelinktoviewtheprint-fidelitycodeimageToreturntothepreviouspageviewedclicktheBackbuttononyourdeviceorapp

  • About This eBook
  • Title Page
  • Copyright Page
  • Contents
  • Preface
    • Improvements in the Python 3 Edition
    • The Hard Way Is Easier
      • Reading and Writing
      • Attention to Detail
      • Spotting Differences
      • Ask Donrsquot Stare
      • Do Not Copy-Paste
      • Using the Included Videos
      • A Note on Practice and Persistence
        • Acknowledgments
          • Exercise 0 The Setup
            • macOS
              • macOS What You Should See
                • Windows
                  • Windows What You Should See
                    • Linux
                      • Linux What You Should See
                        • Finding Things on the Internet
                        • Warnings for Beginners
                        • Alternative Text Editors
                          • Exercise 1 A Good First Program
                            • What You Should See
                            • Study Drills
                            • Common Student Questions
                              • Exercise 2 Comments and Pound Characters
                                • What You Should See
                                • Study Drills
                                • Common Student Questions
                                  • Exercise 3 Numbers and Math
                                    • What You Should See
                                    • Study Drills
                                    • Common Student Questions
                                      • Exercise 4 Variables and Names
                                        • What You Should See
                                        • Study Drills
                                        • Common Student Questions
                                          • Exercise 5 More Variables and Printing
                                            • What You Should See
                                            • Study Drills
                                            • Common Student Questions
                                              • Exercise 6 Strings and Text
                                                • What You Should See
                                                • Study Drills
                                                • Break It
                                                • Common Student Questions
                                                  • Exercise 7 More Printing
                                                    • What You Should See
                                                    • Study Drills
                                                    • Break It
                                                    • Common Student Questions
                                                      • Exercise 8 Printing Printing
                                                        • What You Should See
                                                        • Study Drills
                                                        • Common Student Questions
                                                          • Exercise 9 Printing Printing Printing
                                                            • What You Should See
                                                            • Study Drills
                                                            • Common Student Questions
                                                              • Exercise 10 What Was That
                                                                • What You Should See
                                                                • Escape Sequences
                                                                • Study Drills
                                                                • Common Student Questions
                                                                  • Exercise 11 Asking Questions
                                                                    • What You Should See
                                                                    • Study Drills
                                                                    • Common Student Questions
                                                                      • Exercise 12 Prompting People
                                                                        • What You Should See
                                                                        • Study Drills
                                                                        • Common Student Questions
                                                                          • Exercise 13 Parameters Unpacking Variables
                                                                            • Hold Up Features Have Another Name
                                                                            • What You Should See
                                                                            • Study Drills
                                                                            • Common Student Questions
                                                                              • Exercise 14 Prompting and Passing
                                                                                • What You Should See
                                                                                • Study Drills
                                                                                • Common Student Questions
                                                                                  • Exercise 15 Reading Files
                                                                                    • What You Should See
                                                                                    • Study Drills
                                                                                    • Common Student Questions
                                                                                      • Exercise 16 Reading and Writing Files
                                                                                        • What You Should See
                                                                                        • Study Drills
                                                                                        • Common Student Questions
                                                                                          • Exercise 17 More Files
                                                                                            • What You Should See
                                                                                            • Study Drills
                                                                                            • Common Student Questions
                                                                                              • Exercise 18 Names Variables Code Functions
                                                                                                • What You Should See
                                                                                                • Study Drills
                                                                                                • Common Student Questions
                                                                                                  • Exercise 19 Functions and Variables
                                                                                                    • What You Should See
                                                                                                    • Study Drills
                                                                                                    • Common Student Questions
                                                                                                      • Exercise 20 Functions and Files
                                                                                                        • What You Should See
                                                                                                        • Study Drills
                                                                                                        • Common Student Questions
                                                                                                          • Exercise 21 Functions Can Return Something
                                                                                                            • What You Should See
                                                                                                            • Study Drills
                                                                                                            • Common Student Questions
                                                                                                              • Exercise 22 What Do You Know So Far
                                                                                                                • What You Are Learning
                                                                                                                  • Exercise 23 Strings Bytes and Character Encodings
                                                                                                                    • Initial Research
                                                                                                                    • Switches Conventions and Encodings
                                                                                                                    • Disecting the Output
                                                                                                                    • Disecting the Code
                                                                                                                    • Encodings Deep Dive
                                                                                                                    • Breaking It
                                                                                                                      • Exercise 24 More Practice
                                                                                                                        • What You Should See
                                                                                                                        • Study Drills
                                                                                                                        • Common Student Questions
                                                                                                                          • Exercise 25 Even More Practice
                                                                                                                            • What You Should See
                                                                                                                            • Study Drills
                                                                                                                            • Common Student Questions
                                                                                                                              • Exercise 26 Congratulations Take a Test
                                                                                                                                • Common Student Questions
                                                                                                                                  • Exercise 27 Memorizing Logic
                                                                                                                                    • The Truth Terms
                                                                                                                                    • The Truth Tables
                                                                                                                                    • Common Student Questions
                                                                                                                                      • Exercise 28 Boolean Practice
                                                                                                                                        • What You Should See
                                                                                                                                        • Study Drills
                                                                                                                                        • Common Student Questions
                                                                                                                                          • Exercise 29 What If
                                                                                                                                            • What You Should See
                                                                                                                                            • Study Drills
                                                                                                                                            • Common Student Questions
                                                                                                                                              • Exercise 30 Else and If
                                                                                                                                                • What You Should See
                                                                                                                                                • Study Drills
                                                                                                                                                • Common Student Questions
                                                                                                                                                  • Exercise 31 Making Decisions
                                                                                                                                                    • What You Should See
                                                                                                                                                    • Study Drills
                                                                                                                                                    • Common Student Questions
                                                                                                                                                      • Exercise 32 Loops and Lists
                                                                                                                                                        • What You Should See
                                                                                                                                                        • Study Drills
                                                                                                                                                        • Common Student Questions
                                                                                                                                                          • Exercise 33 While Loops
                                                                                                                                                            • What You Should See
                                                                                                                                                            • Study Drills
                                                                                                                                                            • Common Student Questions
                                                                                                                                                              • Exercise 34 Accessing Elements of Lists
                                                                                                                                                                • Study Drills
                                                                                                                                                                  • Exercise 35 Branches and Functions
                                                                                                                                                                    • What You Should See
                                                                                                                                                                    • Study Drills
                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                      • Exercise 36 Designing and Debugging
                                                                                                                                                                        • Rules for if-statements
                                                                                                                                                                        • Rules for Loops
                                                                                                                                                                        • Tips for Debugging
                                                                                                                                                                        • Homework
                                                                                                                                                                          • Exercise 37 Symbol Review
                                                                                                                                                                            • Keywords
                                                                                                                                                                            • Data Types
                                                                                                                                                                            • String Escape Sequences
                                                                                                                                                                            • Old Style String Formats
                                                                                                                                                                            • Operators
                                                                                                                                                                            • Reading Code
                                                                                                                                                                            • Study Drills
                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                              • Exercise 38 Doing Things to Lists
                                                                                                                                                                                • What You Should See
                                                                                                                                                                                • What Lists Can Do
                                                                                                                                                                                • When to Use Lists
                                                                                                                                                                                • Study Drills
                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                  • Exercise 39 Dictionaries Oh Lovely Dictionaries
                                                                                                                                                                                    • A Dictionary Example
                                                                                                                                                                                    • What You Should See
                                                                                                                                                                                    • What Dictionaries Can Do
                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                      • Exercise 40 Modules Classes and Objects
                                                                                                                                                                                        • Modules Are Like Dictionaries
                                                                                                                                                                                          • Classes Are Like Modules
                                                                                                                                                                                          • Objects Are Like Import
                                                                                                                                                                                          • Getting Things from Things
                                                                                                                                                                                          • A First Class Example
                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                              • Exercise 41 Learning to Speak Object-Oriented
                                                                                                                                                                                                • Word Drills
                                                                                                                                                                                                • Phrase Drills
                                                                                                                                                                                                • Combined Drills
                                                                                                                                                                                                • A Reading Test
                                                                                                                                                                                                • Practice English to Code
                                                                                                                                                                                                • Reading More Code
                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                  • Exercise 42 Is-A Has-A Objects and Classes
                                                                                                                                                                                                    • How This Looks in Code
                                                                                                                                                                                                    • About class Name(object)
                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                      • Exercise 43 Basic Object-Oriented Analysis and Design
                                                                                                                                                                                                        • The Analysis of a Simple Game Engine
                                                                                                                                                                                                          • Write or Draw About the Problem
                                                                                                                                                                                                          • Extract Key Concepts and Research Them
                                                                                                                                                                                                          • Create a Class Hierarchy and Object Map for the Concepts
                                                                                                                                                                                                          • Code the Classes and a Test to Run Them
                                                                                                                                                                                                          • Repeat and Refine
                                                                                                                                                                                                            • Top Down versus Bottom Up
                                                                                                                                                                                                            • The Code for ldquoGothons from Planet Percal 25rdquo
                                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                                              • Exercise 44 Inheritance versus Composition
                                                                                                                                                                                                                • What Is Inheritance
                                                                                                                                                                                                                  • Implicit Inheritance
                                                                                                                                                                                                                  • Override Explicitly
                                                                                                                                                                                                                  • Alter Before or After
                                                                                                                                                                                                                  • All Three Combined
                                                                                                                                                                                                                    • The Reason for super()
                                                                                                                                                                                                                      • Using super() with __init__
                                                                                                                                                                                                                        • Composition
                                                                                                                                                                                                                        • When to Use Inheritance or Composition
                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                          • Exercise 45 You Make a Game
                                                                                                                                                                                                                            • Evaluating Your Game
                                                                                                                                                                                                                            • Function Style
                                                                                                                                                                                                                            • Class Style
                                                                                                                                                                                                                            • Code Style
                                                                                                                                                                                                                            • Good Comments
                                                                                                                                                                                                                            • Evaluate Your Game
                                                                                                                                                                                                                              • Exercise 46 A Project Skeleton
                                                                                                                                                                                                                                • macOSLinux Setup
                                                                                                                                                                                                                                • Windows 10 Setup
                                                                                                                                                                                                                                • Creating the Skeleton Project Directory
                                                                                                                                                                                                                                  • Final Directory Structure
                                                                                                                                                                                                                                    • Testing Your Setup
                                                                                                                                                                                                                                    • Using the Skeleton
                                                                                                                                                                                                                                    • Required Quiz
                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                      • Exercise 47 Automated Testing
                                                                                                                                                                                                                                        • Writing a Test Case
                                                                                                                                                                                                                                        • Testing Guidelines
                                                                                                                                                                                                                                        • What You Should See
                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                          • Exercise 48 Advanced User Input
                                                                                                                                                                                                                                            • Our Game Lexicon
                                                                                                                                                                                                                                              • Breaking Up a Sentence
                                                                                                                                                                                                                                              • Lexicon Tuples
                                                                                                                                                                                                                                              • Scanning Input
                                                                                                                                                                                                                                              • Exceptions and Numbers
                                                                                                                                                                                                                                                • A Test First Challenge
                                                                                                                                                                                                                                                • What You Should Test
                                                                                                                                                                                                                                                • Study Drills
                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                  • Exercise 49 Making Sentences
                                                                                                                                                                                                                                                    • Match and Peek
                                                                                                                                                                                                                                                    • The Sentence Grammar
                                                                                                                                                                                                                                                    • A Word on Exceptions
                                                                                                                                                                                                                                                    • The Parser Code
                                                                                                                                                                                                                                                    • Playing with the Parser
                                                                                                                                                                                                                                                    • What You Should Test
                                                                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                                      • Exercise 50 Your First Website
                                                                                                                                                                                                                                                        • Installing flask
                                                                                                                                                                                                                                                        • Make a Simple ldquoHello Worldrdquo Project
                                                                                                                                                                                                                                                        • Whatrsquos Going On
                                                                                                                                                                                                                                                        • Fixing Errors
                                                                                                                                                                                                                                                        • Create Basic Templates
                                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                                          • Exercise 51 Getting Input from a Browser
                                                                                                                                                                                                                                                            • How the Web Works
                                                                                                                                                                                                                                                            • How Forms Work
                                                                                                                                                                                                                                                            • Creating HTML Forms
                                                                                                                                                                                                                                                            • Creating a Layout Template
                                                                                                                                                                                                                                                            • Writing Automated Tests for Forms
                                                                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                                                                            • Breaking It
                                                                                                                                                                                                                                                              • Exercise 52 The Start of Your Web Game
                                                                                                                                                                                                                                                                • Refactoring the Exercise 43 Game
                                                                                                                                                                                                                                                                • Creating an Engine
                                                                                                                                                                                                                                                                • Your Final Exam
                                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                                  • Next Steps
                                                                                                                                                                                                                                                                    • How to Learn Any Programming Language
                                                                                                                                                                                                                                                                      • Advice from an Old Programmer
                                                                                                                                                                                                                                                                      • Appendix Command Line Crash Course
                                                                                                                                                                                                                                                                        • Introduction Shut Up and Shell
                                                                                                                                                                                                                                                                          • How to Use This Appendix
                                                                                                                                                                                                                                                                          • You Will Be Memorizing Things
                                                                                                                                                                                                                                                                            • The Setup
                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                • Paths Folders Directories (pwd)
                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                    • If You Get Lost
                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                        • Make a Directory (mkdir)
                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                            • Change Directory (cd)
                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                • List Directory (ls)
                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                    • Remove Directory (rmdir)
                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                        • Moving Around (pushd popd)
                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                            • Making Empty Files (touchNew-Item)
                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                • Copy a File (cp)
                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                    • Moving a File (mv)
                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                        • View a File (lessmore)
                                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                                            • Stream a File (cat)
                                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                                • Removing a File (rm)
                                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                                    • Exiting Your Terminal (exit)
                                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                                        • Command Line Next Steps
                                                                                                                                                                                                                                                                                                                                          • Unix Bash References
                                                                                                                                                                                                                                                                                                                                          • PowerShell References
                                                                                                                                                                                                                                                                                                                                              • Index
                                                                                                                                                                                                                                                                                                                                              • Code Snippets
Page 2: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code

LearnPython3TheHardWayAVerySimpleIntroductiontotheTerrifyingly

BeautifulWorldofComputersandCodeZedAShaw

BostonbullColumbusbullIndianapolisbullNewYorkbullSanFranciscobullAmsterdambullCapeTown

DubaibullLondonbullMadridbullMilanbullMunichbullParisbullMontrealbullTorontobullDelhibullMexicoCity

SatildeoPaulobullSydneybullHongKongbullSeoulbullSingaporebullTaipeibullTokyo

ManyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarksWherethosedesignationsappearinthisbookandthepublisherwasawareofatrademarkclaimthedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals

TheauthorandpublisherhavetakencareinthepreparationofthisbookbutmakenoexpressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissionsNoliabilityisassumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseoftheinformationorprogramscontainedherein

Forinformationaboutbuyingthistitleinbulkquantitiesorforspecialsalesopportunities(whichmayincludeelectronicversionscustomcoverdesignsandcontentparticulartoyourbusinesstraininggoalsmarketingfocusorbrandinginterests)pleasecontactourcorporatesalesdepartmentatcorpsalespearsonedcomor(800)382-3419

Forgovernmentsalesinquiriespleasecontactgovernmentsalespearsonedcom

ForquestionsaboutsalesoutsidetheUSpleasecontactintlcspearsoncom

VisitusontheWebinformitcomaw

LibraryofCongressControlNumber2017940290

Copyrightcopy2017ZedAShaw

AllrightsreservedPrintedintheUnitedStatesofAmericaThispublicationisprotectedbycopyrightandpermissionmustbeobtainedfromthepublisherpriortoanyprohibitedreproductionstorageinaretrievalsystemortransmissioninanyformorbyanymeanselectronicmechanicalphotocopyingrecordingorlikewiseForinformationregardingpermissionsrequestformsandtheappropriatecontactswithinthePearsonEducationGlobalRightsampPermissionsDepartmentpleasevisitwwwpearsonedcompermissions

ISBN-13978-0-13-469288-3ISBN-100-13-469288-8

117

Contents

Preface

ImprovementsinthePython3EditionTheHardWayIsEasier

ReadingandWritingAttentiontoDetailSpottingDifferencesAskDonrsquotStareDoNotCopy-PasteUsingtheIncludedVideosANoteonPracticeandPersistence

Acknowledgments

Exercise0TheSetupmacOS

macOSWhatYouShouldSeeWindows

WindowsWhatYouShouldSeeLinux

LinuxWhatYouShouldSeeFindingThingsontheInternetWarningsforBeginnersAlternativeTextEditors

Exercise1AGoodFirstProgramWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise2CommentsandPoundCharactersWhatYouShouldSee

StudyDrillsCommonStudentQuestions

Exercise3NumbersandMathWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise4VariablesandNamesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise5MoreVariablesandPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise6StringsandTextWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise7MorePrintingWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise8PrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise9PrintingPrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise10WhatWasThatWhatYouShouldSeeEscapeSequencesStudyDrillsCommonStudentQuestions

Exercise11AskingQuestionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise12PromptingPeopleWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise13ParametersUnpackingVariablesHoldUpFeaturesHaveAnotherNameWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise14PromptingandPassingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise15ReadingFilesWhatYouShouldSeeStudyDrills

CommonStudentQuestions

Exercise16ReadingandWritingFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise17MoreFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise18NamesVariablesCodeFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise19FunctionsandVariablesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise20FunctionsandFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise21FunctionsCanReturnSomethingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise22WhatDoYouKnowSoFarWhatYouAreLearning

Exercise23StringsBytesandCharacterEncodings

InitialResearchSwitchesConventionsandEncodingsDisectingtheOutputDisectingtheCodeEncodingsDeepDiveBreakingIt

Exercise24MorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise25EvenMorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise26CongratulationsTakeaTestCommonStudentQuestions

Exercise27MemorizingLogicTheTruthTermsTheTruthTablesCommonStudentQuestions

Exercise28BooleanPracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise29WhatIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise30ElseandIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise31MakingDecisionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise32LoopsandListsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise33WhileLoopsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise34AccessingElementsofListsStudyDrills

Exercise35BranchesandFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise36DesigningandDebuggingRulesforif-statementsRulesforLoopsTipsforDebuggingHomework

Exercise37SymbolReview

KeywordsDataTypesStringEscapeSequencesOldStyleStringFormatsOperatorsReadingCodeStudyDrillsCommonStudentQuestions

Exercise38DoingThingstoListsWhatYouShouldSeeWhatListsCanDoWhentoUseListsStudyDrillsCommonStudentQuestions

Exercise39DictionariesOhLovelyDictionariesADictionaryExampleWhatYouShouldSeeWhatDictionariesCanDoStudyDrillsCommonStudentQuestions

Exercise40ModulesClassesandObjectsModulesAreLikeDictionaries

ClassesAreLikeModulesObjectsAreLikeImportGettingThingsfromThingsAFirstClassExample

WhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise41LearningtoSpeakObject-OrientedWordDrillsPhraseDrillsCombinedDrillsAReadingTestPracticeEnglishtoCodeReadingMoreCodeCommonStudentQuestions

Exercise42Is-AHas-AObjectsandClassesHowThisLooksinCodeAboutclassName(object)StudyDrillsCommonStudentQuestions

Exercise43BasicObject-OrientedAnalysisandDesignTheAnalysisofaSimpleGameEngine

WriteorDrawAbouttheProblemExtractKeyConceptsandResearchThemCreateaClassHierarchyandObjectMapfortheConceptsCodetheClassesandaTesttoRunThemRepeatandRefine

TopDownversusBottomUpTheCodeforldquoGothonsfromPlanetPercal25rdquoWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise44InheritanceversusCompositionWhatIsInheritance

ImplicitInheritanceOverrideExplicitlyAlterBeforeorAfter

AllThreeCombinedTheReasonforsuper()

Usingsuper()with__init__CompositionWhentoUseInheritanceorCompositionStudyDrillsCommonStudentQuestions

Exercise45YouMakeaGameEvaluatingYourGameFunctionStyleClassStyleCodeStyleGoodCommentsEvaluateYourGame

Exercise46AProjectSkeletonmacOSLinuxSetupWindows10SetupCreatingtheSkeletonProjectDirectory

FinalDirectoryStructureTestingYourSetupUsingtheSkeletonRequiredQuizCommonStudentQuestions

Exercise47AutomatedTestingWritingaTestCaseTestingGuidelinesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise48AdvancedUserInputOurGameLexicon

BreakingUpaSentenceLexiconTuplesScanningInputExceptionsandNumbers

ATestFirstChallengeWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise49MakingSentencesMatchandPeekTheSentenceGrammarAWordonExceptionsTheParserCodePlayingwiththeParserWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise50YourFirstWebsiteInstallingflaskMakeaSimpleldquoHelloWorldrdquoProjectWhatrsquosGoingOnFixingErrorsCreateBasicTemplatesStudyDrillsCommonStudentQuestions

Exercise51GettingInputfromaBrowserHowtheWebWorksHowFormsWork

CreatingHTMLFormsCreatingaLayoutTemplateWritingAutomatedTestsforFormsStudyDrillsBreakingIt

Exercise52TheStartofYourWebGameRefactoringtheExercise43GameCreatinganEngineYourFinalExamCommonStudentQuestions

NextStepsHowtoLearnAnyProgrammingLanguage

AdvicefromanOldProgrammer

AppendixCommandLineCrashCourseIntroductionShutUpandShell

HowtoUseThisAppendixYouWillBeMemorizingThings

TheSetupDoThisYouLearnedThisDoMore

PathsFoldersDirectories(pwd)DoThisYouLearnedThisDoMore

IfYouGetLostDoThisYouLearnedThis

MakeaDirectory(mkdir)DoThis

YouLearnedThisDoMore

ChangeDirectory(cd)DoThisYouLearnedThisDoMore

ListDirectory(ls)DoThisYouLearnedThisDoMore

RemoveDirectory(rmdir)DoThisYouLearnedThisDoMore

MovingAround(pushdpopd)DoThisYouLearnedThisDoMore

MakingEmptyFiles(touchNew-Item)DoThisYouLearnedThisDoMore

CopyaFile(cp)DoThisYouLearnedThisDoMore

MovingaFile(mv)DoThisYouLearnedThisDoMore

ViewaFile(lessmore)

DoThisYouLearnedThisDoMore

StreamaFile(cat)DoThisYouLearnedThisDoMore

RemovingaFile(rm)DoThisYouLearnedThisDoMore

ExitingYourTerminal(exit)DoThisYouLearnedThisDoMore

CommandLineNextStepsUnixBashReferencesPowerShellReferences

Index

Preface

ThissimplebookismeanttogetyoustartedinprogrammingThetitlesaysitrsquosthehardwaytolearntowritecodebutitrsquosactuallynotItrsquosonlytheldquohardrdquowaybecauseitusesatechniquecalledinstructionInstructioniswhereItellyoutodoasequenceofcontrolledexercisesdesignedtobuildaskillthroughrepetitionThistechniqueworksverywellwithbeginnerswhoknownothingandneedtoacquirebasicskillsbeforetheycanunderstandmorecomplextopicsItrsquosusedineverythingfrommartialartstomusictoevenbasicmathandreadingskillsThisbookinstructsyouinPythonbyslowlybuildingandestablishingskillsthroughtechniquessuchaspracticeandmemorizationthenapplyingthemtoincreasinglydifficultproblemsBytheendofthebookyouwillhavethetoolsneededtobeginlearningmorecomplexprogrammingtopicsIliketotellpeoplethatmybookgivesyouyourldquoprogrammingblackbeltrdquoWhatthismeansisthatyouknowthebasicswellenoughtonowstartlearningprogrammingIfyouworkhardtakeyourtimeandbuildtheseskillsyouwilllearntocode

ImprovementsinthePython3EditionLearnPython3theHardWaynowusesPython36IrsquovestandardizedonthisversionofPythonbecauseithasanewimprovedstringformattingsystemthatiseasiertousethantheprevious4(or3Iforgetthereweremany)versionsThereareafewproblemswithPython36forbeginnersbutIhelpyounavigatetheseissuesinthebookAparticularlyhairyproblemisthatPython36hasverypoorerrormessagesinsomekeyareasthatIhelpyouunderstandIhavealsoimprovedthevideosbasedonmyexperiencesoverthelastfiveyearsteachingpeoplePythonYoucanwatchthesevideosonlineatinformitcomtitle9780134692883InthepastthevideossimplyletyouwatchmedotheexerciseThePython3editionvideosalsoshowyouhowtobreakmdashandthenfixmdasheveryexerciseThisskilliscalledldquodebuggingrdquoItteachesyouhowtofixproblemsyourunintobutalsohowPythonrunstheprogramsyoursquorecreatingThegoalofthisnewmethodologyistobuildamentalmodelofhowPythonrunsyourcodesoyoucanmoreeasilyfigureoutwhyitrsquosbrokenYoursquollalsolearnmanyusefultricksfordebuggingbrokensoftwareLastthePython3editionfullysupportsMicrosoftWindows10frombeginningtoendThepreviouseditionfocusedmostlyontheUnix-stylesystemssuchasmacOSandLinuxwithWindowsbeingmoreofanafterthoughtAtthetimeIstartedwritingthePython3editionMicrosofthadstartedtotakeopensource

startedwritingthePython3editionMicrosofthadstartedtotakeopensourcetoolsanddevelopersseriouslyanditwasdifficulttoignorethemasaseriousPythondevelopmentplatformThevideosfeatureMicrosoftWindowsusingPythoninvariousscenariosandalsoshowmacOSandLinuxforfullcompatibilityItellyouaboutanygotchasoneachplatformcoverinstallationinstructionsandprovideanyothertipsIcangiveyou

TheHardWayIsEasierWiththehelpofthisbookyouwilldotheincrediblysimplethingsthatallprogrammersdotolearnaprogramminglanguage

1Gothrougheachexercise2Typeineachfileexactly3Makeitrun

ThatrsquositThiswillbeverydifficultatfirstbutstickwithitIfyougothroughthisbookanddoeachexerciseforoneortwohoursanightyouwillhaveagoodfoundationformovingontoanotherbookaboutPythontocontinueyourstudiesThisbookwonrsquotturnyouintoaprogrammerovernightbutitwillgetyoustartedonthepathtolearninghowtocodeThisbookrsquosjobistoteachyouthethreemostessentialskillsthatabeginningprogrammerneedstoknowreadingandwritingattentiontodetailandspottingdifferences

ReadingandWritingIfyouhaveaproblemtypingyouwillhaveaproblemlearningtocodeespeciallyifyouhaveaproblemtypingthefairlyoddcharactersinsourcecodeWithoutthissimpleskillyouwillbeunabletolearneventhemostbasicthingsabouthowsoftwareworksTypingthecodesamplesandgettingthemtorunwillhelpyoulearnthenamesofthesymbolsgetfamiliarwithtypingthemandgetyoureadingthelanguage

AttentiontoDetailTheoneskillthatseparatesgoodprogrammersfrombadprogrammersisattentiontodetailInfactitrsquoswhatseparatesthegoodfromthebadinanyprofessionYoumustpayattentiontothetiniestdetailsofyourworkoryouwillmissimportantelementsofwhatyoucreateInprogrammingthisishowyouendupwithbugsanddifficult-to-usesystemsBygoingthroughthisbookandcopyingeachexampleexactlyyouwillbetrainingyourbraintofocusonthedetailsofwhatyouaredoingasyouare

doingit

SpottingDifferencesAveryimportantskill(thatmostprogrammersdevelopovertime)istheabilitytovisuallynoticedifferencesbetweenthingsAnexperiencedprogrammercantaketwopiecesofcodethatareslightlydifferentandimmediatelystartpointingoutthedifferencesProgrammershaveinventedtoolstomakethiseveneasierbutwewonrsquotbeusinganyoftheseYoufirsthavetotrainyourbrainthehardwaythenusethetoolsWhileyoudotheseexercisestypingeachoneinyouwillmakemistakesItrsquosinevitableevenseasonedprogrammerswouldmakeafewYourjobistocomparewhatyouhavewrittentowhatrsquosrequiredandfixallthedifferencesBydoingsoyouwilltrainyourselftonoticemistakesbugsandotherproblems

AskDonrsquotStareIfyouwritecodeyouwillwritebugsAldquobugrdquomeansadefecterrororproblemwiththecodeyoursquovewrittenThelegendssaythatthiscomesfromanactualmoththatflewintooneofthefirstcomputerscausingittomalfunctionFixingitrequiredldquodebuggingrdquothecomputerIntheworldofsoftwaretherearealotofbugsSomanyLikethatfirstmothyourbugswillbehiddensomewhereinthecodeandyouhavetogofindthemYoucanrsquotjustsitatyourcomputerscreenstaringatthewordsyoursquovewrittenhopingthattheanswerjumpsoutatyouThereisnomoreadditionalinformationyoucangetdoingthatandyouneedadditionalinformationYouneedtogetupandgofindthemothTodothatyouhavetointerrogateyourcodeandaskitwhatisgoingonorlookattheproblemfromadifferentviewInthisbookIfrequentlytellyoutoldquostopstaringandaskrdquoIshowyouhowtomakeyourcodetellyoueverythingitcanaboutwhatrsquosgoingonandhowtoturnthisintopossiblesolutionsIalsoshowyouhowtoseeyourcodeindifferentwayssoyoucangetmoreinformationandinsight

DoNotCopy-PasteYoumusttypeeachoftheseexercisesinmanuallyIfyoucopy-pasteyoumightaswellnotevendothemThepointoftheseexercisesistotrainyourhandsyourbrainandyourmindinhowtoreadwriteandseecodeIfyoucopy-pasteyouarecheatingyourselfoutoftheeffectivenessofthelessons

UsingtheIncludedVideos

LearnPython3theHardWayhasanextensivesetofvideosdemonstratinghowthecodeworksandmostimportantlyhowtobreakitThevideosaretheperfectplacetodemonstratemanycommonerrorsbybreakingthePythoncodeonpurposeandshowingyouhowtofixitIalsowalkthroughthecodeusingdebuggingandinterrogationtricksandtechniquesThevideosarewhereIshowyouhowtoldquostopstaringandaskrdquothecodewhatrsquoswrongYoucanwatchthesevideosonlineatinformitcomtitle9780134692883

ANoteonPracticeandPersistenceWhileyouarestudyingprogrammingIrsquomstudyinghowtoplayguitarIpracticeiteverydayforatleasttwohoursadayIplayscaleschordsandarpeggiosforanhourandthenlearnmusictheoryeartrainingsongsandanythingelseIcanSomedaysIstudyguitarandmusicforeighthoursbecauseIfeellikeitanditrsquosfunTomerepetitivepracticeisnaturalandjusthowtolearnsomethingIknowthattogetgoodatanythingIhavetopracticeeverydayevenifIsuckthatday(whichisoften)oritrsquosdifficultKeeptryingandeventuallyitrsquollbeeasierandfunBetweenthetimethatIwroteLearnPythontheHardWayandLearnRubytheHardWayIdiscovereddrawingandpaintingIfellinlovewithmakingvisualartattheageof39andhavebeenspendingeverydaystudyingitinmuchthesamewaythatIstudiedguitarmusicandprogrammingIcollectedbooksofinstructionalmaterialdidwhatthebookssaidpaintedeverydayandfocusedonenjoyingtheprocessoflearningIambynomeansanldquoartistrdquooreventhatgoodbutIcannowsaythatIcandrawandpaintThesamemethodIrsquomteachingyouinthisbookappliedtomyadventuresinartIfyoubreaktheproblemdownintosmallexercisesandlessonsanddothemeverydayyoucanlearntodoalmostanythingIfyoufocusonslowlyimprovingandenjoyingthelearningprocessthenyouwillbenefitnomatterhowgoodyouareatitAsyoustudythisbookandcontinuewithprogrammingrememberthatanythingworthdoingisdifficultatfirstMaybeyouarethekindofpersonwhoisafraidoffailuresoyougiveupatthefirstsignofdifficultyMaybeyouneverlearnedself-disciplinesoyoucanrsquotdoanythingthatrsquosldquoboringrdquoMaybeyouweretoldthatyouareldquogiftedrdquosoyouneverattemptanythingthatmightmakeyouseemstupidornotaprodigyMaybeyouarecompetitiveandunfairlycompareyourselftosomeonelikemewhorsquosbeenprogrammingformorethan20yearsWhateveryourreasonforwantingtoquitkeepatitForceyourselfIfyourunintoaStudyDrillyoucanrsquotdooralessonyoujustdonotunderstandthenskip

itandcomebacktoitlaterJustkeepgoingbecausewithprogrammingtherersquosthisveryoddthingthathappensAtfirstyouwillnotunderstandanythingItrsquollbeweirdjustlikewithlearninganyhumanlanguageYouwillstrugglewithwordsandnotknowwhatsymbolsarewhatanditrsquollallbeveryconfusingThenonedayBANGmdashyourbrainwillsnapandyouwillsuddenlyldquogetitrdquoIfyoukeepdoingtheexercisesandkeeptryingtounderstandthemyouwillgetitYoumightnotbeamastercoderbutyouwillatleastunderstandhowprogrammingworksIfyougiveupyouwonrsquoteverreachthispointYouwillhitthefirstconfusingthing(whichiseverythingatfirst)andthenstopIfyoukeeptryingkeeptypingitinkeeptryingtounderstanditandreadingaboutityouwilleventuallygetitIfyougothroughthiswholebookandyoustilldonotunderstandhowtocodeatleastyougaveitashotYoucansayyoutriedyourbestandalittlemoreanditdidnrsquotworkoutbutatleastyoutriedYoucanbeproudofthat

RegisteryourcopyofLearnPython3theHardWayontheInformITsiteforconvenientaccesstoupdatesandcorrectionsastheybecomeavailableTostarttheregistrationprocessgotoinformitcomregisterandloginorcreateanaccountEntertheproductISBN(9780134692883)andanswerthesimpleproof-of-purchasequestionThenlookontheRegisteredProductstabforanAccessBonusContentlinknexttothisproductandfollowthatlinktoaccessthebonusmaterials

AcknowledgmentsIwouldliketothankAngelaforhelpingmewiththefirsttwoversionsofthisbookWithoutherIprobablywouldnrsquothavebotheredtofinishitatallShedidthecopyeditingofthefirstdraftandsupportedmeimmenselywhileIwroteitIrsquodalsoliketothankGregNewmanfordoingtheoriginalcoverartBrianShumateforearlywebsitedesignsandallofthepeoplewhoreadthisbookandtookthetimetosendmefeedbackandcorrectionsThankyou

Exercise0TheSetup

ThisexercisehasnocodeItissimplytheexerciseyoucompletetogetyourcomputertorunPythonYoushouldfollowtheseinstructionsasexactlyaspossibleIfyouhaveproblemsfollowingthewritteninstructionsthenwatchtheincludedvideosforyourplatform

WarningIfyoudonotknowhowtousePowerShellonWindowsTerminalonmacOSorbashonLinuxthenyouneedtogolearnthatfirstYoushoulddotheexercisesintheappendixfirstbeforecontinuingwiththeseexercises

macOSDothefollowingtaskstocompletethisexercise

1Gotohttpswwwpythonorgdownloadsreleasepython-360anddownloadtheversiontitledldquoMacOSX64-bit32-bitinstallerrdquoInstallitlikeyouwouldanyothersoftware

2GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3PutAtom(yourtexteditor)inyourdocksoyoucanreachiteasily4FindyourTerminalprogramSearchforitYouwillfindit5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthenameandhittingRETURN

8Typequit()Enterandgetoutofpython369YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryintheTerminal11LearnhowtochangeintoadirectoryintheTerminal12UseyoureditortocreateafileinthisdirectoryMakethefileSaveor

SaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindows14BackinTerminallistthedirectorywithlstoseeyournewlycreatedfile

macOSWhatYouShouldSeeHerersquosmedoingthisonmymacOScomputerinTerminalYourcomputermightbedifferentbutshouldbesimilartothisClickheretoviewcodeimage

$python36

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clangndash700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgt

~$mkdirlpthw

~$cdlpthw

lpthw$ls

Useyourtexteditorheretoedittesttxt

lpthw$ls

testtxt

lpthw$

Windows1GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitYoudonotneedtobetheadministratortodothis

2MakesureyoucangettoAtomeasilybyputtingitonyourdesktopandorinQuickLaunchBothoptionsareavailableduringsetupIfyoucannotrunAtombecauseyourcomputerisnotfastenoughthenseetheAlternativeTextEditorssectionattheendofthisexercise

3RunPowerShellfromtheStartmenuSearchforitandjustpressEntertorunit

4MakeashortcuttoitonyourdesktopandorQuickLaunchforyourconvenience

5RunyourPowerShellprogram(whichIwillcallTerminallater)Itwonrsquotlooklikemuch

6DownloadPython36fromhttpswwwpythonorgdownloadsreleasepython-360andinstallitBesuretochecktheboxthatsaystoaddPython36toyourpath

7InyourPowerShell(Terminal)programrunpythonYourunthingsinTerminalbyjusttypingthenameandpressingEnterIfyoutypepythonanditdoesnotrunthenyouhavetoreinstallPythonandmakesureyouchecktheboxforldquoAddpythontothePATHrdquoItrsquosverysmallsolookcarefully

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinthePowerShell(Terminal)11LearnhowtochangeintoadirectoryinthePowerShell(Terminal)12UseyoureditortocreateafileinthisdirectoryMakethefileSaveorSaveAsandpickthisdirectory

13GobacktoPowerShell(Terminal)usingjustthekeyboardtoswitchwindowsLookitupifyoucanrsquotfigureitout

14BackinPowerShell(Terminal)listthedirectorytoseeyournewlycreatedfile

FromnowonwhenIsayldquoTerminalrdquoorldquoshellrdquoImeanPowerShellandthatrsquoswhatyoushoulduseWhenIrunpython36youcanjusttypepython

WindowsWhatYouShouldSeeClickheretoviewcodeimage

gtpython

gtgtgtquit()

gtmkdirlpthw

gtcdlpthw

Hereyouwoulduseyourtexteditortomaketesttxtinlpthw

gt

gtdir

VolumeindriveCis

VolumeSerialNumberis085C-7E02

DirectoryofCDocumentsandSettingsyoulpthw

040520102332ltDIRgt

040520102332ltDIRgt

0405201023326testtxt

1File(s)6bytes

2Dir(s)14804623360bytesfree

gt

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

LinuxLinuxisavariedoperatingsystemwithmanydifferentwaystoinstallsoftwareIrsquomassumingifyouarerunningLinuxthenyouknowhowtoinstallpackagessohereareyourinstructions

1UseyourpackagemanagertoinstallPython36andifyoucanrsquotthendownloadsourcefromhttpswwwpythonorgdownloadsreleasepython-360andbuildfromsource

2UseyourLinuxpackagemanagerandinstalltheAtomtexteditorIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3MakesureyoucangettoAtomeasilybyputtingitinyourwindowmanagerrsquosmenu

4FindyourTerminalprogramItcouldbecalledGNOMETerminalKonsoleorxterm

5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthecommandnameandpressingEnterIfyoucanrsquotrunpython36tryrunningjustpython

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinTerminal11LearnhowtochangeintoadirectoryinTerminal12UseyoureditortocreateafileinthisdirectoryTypicallyyouwillmake

thefileSaveorSaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindowsLookit

upifyoucanrsquotfigureitout14BackinTerminallistthedirectorytoseeyournewlycreatedfile

LinuxWhatYouShouldSee

Clickheretoviewcodeimage

$python

gtgtgtquit()

$mkdirlpthw

$cdlpthw

Useyourtexteditorheretoedittesttxt

$ls

testtxt

$

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

FindingThingsontheInternetAmajorpartofthisbookislearningtoresearchprogrammingtopicsonlineIrsquolltellyoutoldquosearchforthisontheinternetrdquoandyourjobistouseasearchenginetofindtheanswerThereasonIhaveyousearchinsteadofjustgivingyoutheanswerisbecauseIwantyoutobeanindependentlearnerwhodoesnotneedmybookwhenyoursquoredonewithitIfyoucanfindtheanswerstoyourquestionsonlinethenyouareonestepclosertonotneedingmeandthatismygoalThankstosearchenginessuchasGoogleyoucaneasilyfindanythingItellyoutofindIfIsayldquosearchonlineforthepythonlistfunctionsrdquothenyousimplydothis

1Gotohttpgooglecom2Typepython3listfunctions3Readthewebsiteslistedtofindthebestanswer

WarningsforBeginnersYouaredonewiththisexerciseThisexercisemightbehardforyoudependingonyourfamiliaritywithyourcomputerIfitisdifficulttakethetimetoreadandstudyandgetthroughitbecauseuntilyoucandotheseverybasicthingsyouwillfinditdifficulttogetmuchprogrammingdoneIfsomeonetellsyoutostopataspecificexerciseinthisbookortoskipcertainonesyoushouldignorethatpersonAnyonetryingtohideknowledgefromyouorworsemakeyougetitfromtheminsteadofthroughyourowneffortsistryingtomakeyoudependonthemforyourskillsDonrsquotlistentothemanddotheexercisesanywaysothatyoulearnhowtoeducateyourselfAprogrammerwilleventuallytellyoutousemacOSorLinuxIftheprogrammerlikesfontsandtypographytheyrsquolltellyoutogetamacOScomputerIfhelikescontrolandhasahugebeardhewill(orzewillifyou

computerIfhelikescontrolandhasahugebeardhewill(orzewillifyouprefernon-genderedpronounsforhumanswithbeards)tellyoutoinstallLinuxAgainusewhatevercomputeryouhaverightnowthatworksAllyouneedisaneditoraTerminalandPythonFinallythepurposeofthissetuphelpsyoudothreethingsveryreliablywhileyouworkontheexercises

1Writeexercisesusingthetexteditor2Runtheexercisesyouwrote3Fixthemwhentheyarebroken4Repeat

Anythingelsewillonlyconfuseyousosticktotheplan

AlternativeTextEditorsTexteditorsareveryimportanttoaprogrammerbutasabeginneryouonlyneedasimpleprogrammerrsquostexteditorThesearedifferentfromsoftwareforwritingstoriesandbooksbecausetheyworkwiththeuniqueneedsofcomputercodeIrecommendAtominthisbookbecauseitisfreeandworksnearlyeverywhereHoweverAtommaynotrunwellonyourcomputersoherearesomealternativestotry

ThesearerankedinorderofmostlikelytoworkKeepinmindthattheseprojectsmaybeabandoneddeadornotworkanymoreonyourcomputerIfyoutryoneanditdoesnrsquotworktryanotheroneIrsquovealsolistedtheldquoWorksOnrdquoinorderofmostlikelytoworksoifyoursquoreonWindowsthenlookattheeditorswhereWindowsislistedfirstintheldquoWorksOnrdquocolumnIfyoualreadyknowhowtouseVimorEmacsthenfeelfreetousethemIfyouhaveneverusedVimorEmacsthenavoidthemProgrammersmaytrytoconvinceyoutouseVimorEmacsbutthiswillonlyderailyouYourfocusislearningPythonnotlearningVimorEmacsIfyoutrytouseVimanddonrsquotknowhowtoquitthentypeqorZZIfsomeonetoldyoutouseVimand

theydidnrsquoteventellyouthisthennowyouknowwhyyoushouldnrsquotlistentothemDonotuseanIntegratedDevelopmentEnvironment(IDE)whileyougothroughthisbookRelyingonanIDEmeansthatyoucanrsquotworkwithnewprogramminglanguagesuntilsomecompanydecidestosellyouanIDEforthatlanguageThismeansyoucanrsquotusethatnewlanguageuntilthelanguageislargeenoughtojustifyalucrativecustomerbaseIfyouareconfidentyoucanworkwithonlyaprogrammerrsquostexteditor(likeVimEmacsAtometc)thenyoudonrsquothavetowaitforathirdpartyIDEsareniceinsomesituations(suchasworkingwithagiantexistingcodebase)butbeingaddictedtothemwilllimityourfutureYoushouldalsonotuseIDLEIthasseriouslimitationsinhowitworksandisnrsquotaverygoodpieceofsoftwareAllyouneedisasimpletexteditorashellandPython

Exercise1AGoodFirstProgram

WarningIfyouskippedExercise0thenyouarenotdoingthisbookrightAreyoutryingtouseIDLEoranIDEIsaidnottouseoneinExercise0soyoushouldnotuseoneIfyouskippedExercise0pleasegobacktoitandreadit

YoushouldhavespentagoodamountoftimeinExercise0learninghowtoinstallatexteditorrunthetexteditorruntheTerminalandworkwithbothofthemIfyouhavenrsquotdonethatthendonotgoonYouwillnothaveagoodtimeThisistheonlytimeIrsquollstartanexercisewithawarningthatyoushouldnotskiporgetaheadofyourselfTypethefollowingtextintoasinglefilenamedex1pyPythonworksbestwithfilesendinginpyClickheretoviewcodeimage

ex1py

1print(HelloWorld)

2print(HelloAgain)

3print(Iliketypingthis)

4print(Thisisfun)

5print(YayPrinting)

6print(Idmuchratheryounot)

7print(Isaiddonottouchthis)

YourAtomtexteditorshouldlooksomethinglikethisonallplatforms

DonrsquotworryifyoureditordoesnrsquotlookexactlythesameitshouldbeclosethoughYoumayhaveaslightlydifferentwindowheadermaybeslightlydifferentcolorsandtheleftsideofyourAtomwindowwonrsquotsayldquozedshawrdquobutwillinsteadshowthedirectoryyouusedforsavingyourfilesAllofthosedifferencesarefineWhenyoucreatethisfilekeepinmindthesepoints

1IdidnottypethelinenumbersontheleftThoseareprintedinthebooksoIcantalkaboutspecificlinesbysayingldquoSeeline5rdquoYoudonottypelinenumbersintoPythonscripts

2IhavetheprintatthebeginningofthelineanditlooksexactlythesameaswhatIhaveinex1pyExactlymeansexactlynotkindofsortofthesameEverysinglecharacterhastomatchforittoworkColordoesnrsquot

matteronlythecharactersyoutypeInmacOSTerminalor(maybe)Linuxrunthefilebytyping

python36ex1py

OnWindowsrememberyoualwaystypepythoninsteadofpython36likethis

pythonex1py

IfyoudiditrightthenyoushouldseethesameoutputasIintheWhatYouShouldSeesectionofthisexerciseIfnotyouhavedonesomethingwrongNothecomputerisnotwrong

WhatYouShouldSeeOnmacOSintheTerminalyoushouldseethis

OnWindowsinPowerShellyoushouldseethis

Youmayseedifferentnamesbeforethepython36ex1pycommandbuttheimportantpartisthatyoutypethecommandandseetheoutputisthesameasmineIfyouhaveanerroritwilllooklikethisClickheretoviewcodeimage

$python36pythonex1py

Filepythonex1pyline3

print(Iliketypingthis

^

SyntaxErrorEOLwhilescanningstringliteral

ItrsquosimportantthatyoucanreadtheseerrormessagesbecauseyouwillbemakingmanyofthesemistakesEvenImakemanyofthesemistakesLetrsquoslookatthislinebyline

1WeranourcommandintheTerminaltoruntheex1pyscript2Pythontellsusthatthefileex1pyhasanerroronline3ofex1py3Itprintsthislineofcodeforustoseeit4Thenitputsa^(caret)charactertopointatwheretheproblemisNoticethemissing(double-quote)character

5FinallyitprintsoutaldquoSyntaxErrorrdquoandtellsussomethingaboutwhatmightbetheerrorUsuallytheseareverycrypticbutifyoucopythattext

mightbetheerrorUsuallytheseareverycrypticbutifyoucopythattextintoasearchengineyouwillfindsomeoneelsewhorsquoshadthaterrorandyoucanprobablyfigureouthowtofixit

StudyDrillsTheStudyDrillscontainthingsyoushouldtrytodoIfyoucanrsquotskipitandcomebacklaterForthisexercisetrythesethings

1Makeyourscriptprintanotherline2Makeyourscriptprintonlyoneofthelines3Puta(octothorpe)characteratthebeginningofalineWhatdiditdoTrytofindoutwhatthischaracterdoes

FromnowonIwonrsquotexplainhoweachexerciseworksunlessanexerciseisdifferent

WarningAnldquooctothorperdquoisalsocalledaldquopoundrdquoldquohashrdquoldquomeshrdquooranynumberofothernamesPicktheonethatmakesyouchillout

CommonStudentQuestionsTheseareactualquestionsthatrealstudentshaveaskedwhendoingthisexercise

CanIuseIDLENoyoushoulduseTerminalonmacOSandPowerShellonWindowsjustlikeIhavehereIfyoudonrsquotknowhowtousethosethenyoucangoreadtheappendix

HowdoyougetcolorsinyoureditorSaveyourfilefirstasapyfilesuchasex1pyThenyoursquollhavecolorwhenyoutype

IgetSyntaxErrorinvalidsyntaxwhenIrunex1pyYouareprobablytryingtorunPythonthentryingtotypePythonagainCloseyourTerminalstartitagainandrightawaytypeonlypython36ex1py

Igetcantopenfileex1py[Errno2]NosuchfileordirectoryYouneedtobeinthesamedirectoryasthefileyoucreatedMakesureyouusethecdcommandtogotherefirstForexampleifyousavedyourfileinlpthwex1pythenyouwoulddocdlpthwbeforetryingtorunpython36

ex1pyIfyoudonrsquotknowwhatanyofthatmeansthengothroughtheappendix

MyfiledoesnrsquotrunIjustgetthepromptbackwithnooutputYoumostlikelytookthecodeinmyex1pyfileliterallyandthoughtthatprint(HelloWorld)meanttotypeonlyHelloWorldintothefilewithouttheprintYourfilehastobeexactlylikemine

Exercise2CommentsandPoundCharacters

CommentsareveryimportantinyourprogramsTheyareusedtotellyouwhatsomethingdoesinEnglishandtheyareusedtodisablepartsofyourprogramifyouneedtoremovethemtemporarilyHerersquoshowyouusecommentsinPythonClickheretoviewcodeimage

ex2py

1Acommentthisissoyoucanreadyourprogramlater

2Anythingaftertheisignoredbypython

3

4print(Icouldhavecodelikethis)andthecommentafteris

ignored

5

6Youcanalsouseacommenttodisableorcommentoutcode

7print(Thiswontrun)

8

9print(Thiswillrun)

FromnowonIrsquomgoingtowritecodelikethisItisimportantforyoutounderstandthateverythingdoesnothavetobeliteralYourscreenandprogrammayvisuallylookdifferentbutwhatrsquosimportantisthetextyoutypeintothefileyoursquorewritinginyourtexteditorInfactIcouldworkwithanytexteditorandtheresultswouldbethesame

WhatYouShouldSee

Exercise2Session

$python36ex2py

Icouldhavecodelikethis

Thiswillrun

AgainIrsquomnotgoingtoshowyouscreenshotsofalltheTerminalspossibleYoushouldunderstandthattheprecedingisnotaliteraltranslationofwhatyouroutputshouldlooklikevisuallybutthetextbetweenthefirst$python36andlast$lineswillbewhatyoufocuson

StudyDrills

1Findoutifyouwererightaboutwhatthecharacterdoesandmakesureyouknowwhatitrsquoscalled(octothorpeorpoundcharacter)

2Takeyourex2pyfileandrevieweachlinegoingbackwardStartatthelastlineandcheckeachwordinreverseagainstwhatyoushouldhavetyped

3DidyoufindmoremistakesFixthem4ReadwhatyoutypedaboveoutloudincludingsayingeachcharacterbyitsnameDidyoufindmoremistakesFixthem

CommonStudentQuestionsAreyousureiscalledthepoundcharacterIcallittheoctothorpebecausethatistheonlynamethatnoonecountryusesandthatworksineverycountryEverycountrythinksitsnameforthisonecharacterisboththemostimportantwaytodoitandtheonlywayitrsquosdoneTomethisissimplyarroganceandreallyyrsquoallshouldjustchilloutandfocusonmoreimportantthingslikelearningtocode

Whydoestheinprint(Hithere)notgetignoredTheinthatcodeisinsideastringsoitwillbeputintothestringuntiltheendingcharacterishitPoundcharactersinstringsarejustconsideredcharactersnotcomments

HowdoIcommentoutmultiplelinesPutainfrontofeachoneIcanrsquotfigureouthowtotypeacharacteronmycountryrsquoskeyboardHowdoIdothatSomecountriesusetheALTkeyandcombinationsofotherkeystoprintcharactersforeigntotheirlanguageYoursquollhavetolookonlineinasearchenginetoseehowtotypeit

WhydoIhavetoreadcodebackwardItrsquosatricktomakeyourbrainnotattachmeaningtoeachpartofthecodeanddoingthatmakesyouprocesseachpieceexactlyThisisahandyerror-checkingtechnique

Exercise3NumbersandMath

EveryprogramminglanguagehassomekindofwayofdoingnumbersandmathDonotworryprogrammersfrequentlylieaboutbeingmathgeniuseswhentheyreallyarenrsquotIftheyweremathgeniusestheywouldbedoingmathnotwritingbuggywebframeworkssotheycandriveracecarsThisexercisehaslotsofmathsymbolsLetrsquosnamethemrightawaysoyouknowwhattheyarecalledAsyoutypethisoneinsaythenameWhensayingthemfeelsboringyoucanstopsayingthemHerearethenamesbull+plusbull-minusbullslashbullasteriskbullpercentbullltless-thanbullgtgreater-thanbulllt=less-than-equalbullgt=greater-than-equalNoticehowtheoperationsaremissingAfteryoutypeinthecodeforthisexercisegobackandfigureoutwhateachofthesedoesandcompletethetableForexample+doesadditionClickheretoviewcodeimage

ex3py

1print(Iwillnowcountmychickens)

2

3print(Hens25+306)

4print(Roosters100-2534)

5

6print(NowIwillcounttheeggs)

7

8print(3+2+1-5+42-14+6)

9

10print(Isittruethat3+2lt5-7)

11

12print(3+2lt5-7)

13

14print(Whatis3+23+2)

15print(Whatis5-75-7)

16

17print(OhthatswhyitsFalse)

18

19print(Howaboutsomemore)

20

21print(Isitgreater5gt-2)

22print(Isitgreaterorequal5gt=-2)

23print(Isitlessorequal5lt=-2)Makesureyoutypethis

exactlybeforeyourunitCompareeachlineofyourfiletomyfile

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise3Session

$python36ex3py

Iwillnowcountmychickens

Hens300

Roosters97

NowIwillcounttheeggs

675

Isittruethat3+2lt5-7

False

Whatis3+25

Whatis5-7-2

OhthatswhyitsFalse

Howaboutsomemore

IsitgreaterTrue

IsitgreaterorequalTrue

IsitlessorequalFalse

StudyDrills1Aboveeachlineusethetowriteacommenttoyourselfexplainingwhatthelinedoes

2RememberinExercise0whenyoustartedpython36Startpython36thiswayagainandusingthemathoperatorsusePythonasacalculator

3Findsomethingyouneedtocalculateandwriteanewpyfilethatdoesit

4Rewriteex3pytousefloatingpointnumberssoitrsquosmoreaccurate200isfloatingpoint

CommonStudentQuestionsWhyisthecharacteraldquomodulusrdquoandnotaldquopercentrdquoMostlythatrsquosjusthowthedesignerschosetousethatsymbolInnormalwritingyouarecorrecttoreaditasaldquopercentrdquoInprogrammingthiscalculationistypicallydonewithsimpledivisionandtheoperatorThemodulusisadifferentoperationthatjusthappenstousethesymbol

HowdoesworkAnotherwaytosayitisldquoXdividedbyYwithJ

remainingrdquoForexampleldquo100dividedby16with4remainingrdquoTheresultofistheJpartortheremainingpart

WhatistheorderofoperationsIntheUnitedStatesweuseanacronymcalledPEMDASwhichstandsforParenthesesExponentsMultiplicationDivisionAdditionSubtractionThatrsquostheorderPythonfollowsaswellThemistakepeoplemakewithPEMDASistothinkthisisastrictorderasinldquoDoPthenEthenMthenDthenAthenSrdquoTheactualorderisyoudothemultiplicationanddivision(MampD)inonestepfromlefttorightthenyoudotheadditionandsubtractioninonestepfromlefttorightSoyoucouldrewritePEMDASasPE(MampD)(AampS)

Exercise4VariablesandNames

NowyoucanprintthingswithprintandyoucandomathThenextstepistolearnaboutvariablesInprogrammingavariableisnothingmorethananameforsomethingsimilartohowmynameldquoZedrdquoisanameforldquothehumanwhowrotethisbookrdquoProgrammersusethesevariablenamestomaketheircodereadmorelikeEnglishandbecausetheyhavelousymemoriesIftheydidnrsquotusegoodnamesforthingsintheirsoftwaretheyrsquodgetlostwhentheytriedtoreadtheircodeagainIfyougetstuckwiththisexerciserememberthetricksyouhavebeentaughtsofaroffindingdifferencesandfocusingondetails1WriteacommentaboveeachlineexplainingtoyourselfinEnglishwhatitdoes

2Readyourpyfilebackward3Readyourpyfileoutloudsayingeventhecharacters

Clickheretoviewcodeimage

ex4py

1cars=100

2space_in_a_car=40

3drivers=30

4passengers=90

5cars_not_driven=cars-drivers

6cars_driven=drivers

7carpool_capacity=cars_drivenspace_in_a_car

8average_passengers_per_car=passengerscars_driven

9

10

11print(Therearecarscarsavailable)

12print(Thereareonlydriversdriversavailable)

13print(Therewillbecars_not_drivenemptycarstoday)

14print(Wecantransportcarpool_capacitypeopletoday)

15print(Wehavepassengerstocarpooltoday)

16print(Weneedtoputaboutaverage_passengers_per_car

17ineachcar)

WarningThe_inspace_in_a_cariscalledanunderscorecharacterFindouthowtotypeitifyoudonotalreadyknowWeusethischaracteralotto

putanimaginaryspacebetweenwordsinvariablenames

WhatYouShouldSeeClickheretoviewcodeimage

Exercise4Session

$python36ex4py

Thereare100carsavailable

Thereareonly30driversavailable

Therewillbe70emptycarstoday

Wecantransport1200peopletoday

Wehave90tocarpooltoday

Weneedtoputabout30ineachcar

StudyDrillsWhenIwrotethisprogramthefirsttimeIhadamistakeandPythontoldmeaboutitlikethisClickheretoviewcodeimage

Traceback(mostrecentcalllast)

Fileex4pyline8inltmodulegt

average_passengers_per_car=car_pool_capacitypassenger

NameErrornamecar_pool_capacityisnotdefined

ExplainthiserrorinyourownwordsMakesureyouuselinenumbersandexplainwhyHerearemorestudydrills1Iused40forspace_in_a_carbutisthatnecessaryWhathappensifitrsquosjust4

2Rememberthat40isafloatingpointnumberItrsquosjustanumberwithadecimalpointandyouneed40insteadofjust4sothatitisfloatingpoint

3Writecommentsaboveeachofthevariableassignments4Makesureyouknowwhat=iscalled(equals)andthatitspurposeistogivedata(numbersstringsetc)names(cars_drivenpassengers)

5Rememberthat_isanunderscorecharacter6Tryrunningpython36fromtheTerminalasacalculatorlikeyoudidbeforeandusevariablenamestodoyourcalculationsPopularvariablenamesincludeixandj

CommonStudentQuestions

CommonStudentQuestionsWhatisthedifferencebetween=(single-equal)and==(double-equal)The=(single-equal)assignsthevalueontherighttoavariableontheleftThe==(double-equal)testswhethertwothingshavethesamevalueYoursquolllearnaboutthisinExercise27

Canwewritex=100insteadofx=100YoucanbutitrsquosbadformYoushouldaddspacearoundoperatorslikethissothatitrsquoseasiertoread

WhatdoyoumeanbyldquoreadthefilebackwardrdquoVerysimpleImagineyouhaveafilewith16linesofcodeinitStartatline16andcompareittomyfileatline16Thendoitagainfor15andsoonuntilyoursquovereadthewholefilebackward

Whydidyouuse40forspace_in_a_carItismostlysoyoucanthenfindoutwhatafloatingpointnumberisandaskthisquestionSeetheStudyDrills

Exercise5MoreVariablesandPrinting

NowwersquolldoevenmoretypingofvariablesandprintingthemoutThistimewersquollusesomethingcalledaformatstringEverytimeyouput(double-quotes)aroundapieceoftextyouhavebeenmakingastringAstringishowyoumakesomethingthatyourprogrammightgivetoahumanYouprintstringssavestringstofilessendstringstowebserversamongmanyotherthingsStringsarereallyhandysointhisexerciseyouwilllearnhowtomakestringsthathavevariablesembeddedinthemYouembedvariablesinsideastringbyusingaspecialsequenceandthenputthevariableyouwantinsidethecharactersYoualsomuststartthestringwiththeletterfforldquoformatrdquoasinfHellosomevarThislittlefbeforethe(double-quote)andthecharacterstellPython3ldquoHeythisstringneedstobeformattedPutthesevariablesinthererdquoAsusualjusttypethisinevenifyoudonotunderstanditandmakeitexactlythesameClickheretoviewcodeimage

ex5py

1my_name=ZedAShaw

2my_age=35notalie

3my_height=74inches

4my_weight=180lbs

5my_eyes=Blue

6my_teeth=White

7my_hair=Brown

8

9print(fLetstalkaboutmy_name)

10print(fHesmy_heightinchestall)

11print(fHesmy_weightpoundsheavy)

12print(Actuallythatsnottooheavy)

13print(fHesgotmy_eyeseyesandmy_hairhair)

14print(fHisteethareusuallymy_teethdependingonthe

coffee)

15

16thislineistrickytrytogetitexactlyright

17total=my_age+my_height+my_weight

18print(fIfIaddmy_agemy_heightandmy_weightIget

total)

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise5Session

$python36ex5py

LetstalkaboutZedAShaw

Hes74inchestall

Hes180poundsheavy

Actuallythatsnottooheavy

HesgotBlueeyesandBrownhair

HisteethareusuallyWhitedependingonthecoffee

IfIadd3574and180Iget289

StudyDrills1Changeallthevariablessothereisnomy_infrontofeachoneMakesureyouchangethenameeverywherenotjustwhereyouused=tosetthem

2TrytowritesomevariablesthatconverttheinchesandpoundstocentimetersandkilogramsDonotjusttypeinthemeasurementsWorkoutthemathinPython

CommonStudentQuestionsCanImakeavariablelikethis1=ZedShawNo1isnotavalidvariablenameTheyneedtostartwithacharactersoa1wouldworkbut1willnot

HowcanIroundafloatingpointnumberYoucanusetheround()functionlikethisround(17333)

WhydoesthisnotmakesensetomeTrymakingthenumbersinthisscriptyourmeasurementsItrsquosweirdbuttalkingaboutyourselfwillmakeitseemmorerealAlsoyoursquorejuststartingoutsoitwonrsquotmaketoomuchsenseKeepgoingandmoreexerciseswillexplainitmore

Exercise6StringsandText

WhileyouhavebeenwritingstringsyoustilldonotknowwhattheydoInthisexercisewecreateabunchofvariableswithcomplexstringssoyoucanseewhattheyareforFirstanexplanationofstringsAstringisusuallyabitoftextyouwanttodisplaytosomeoneorldquoexportrdquooutoftheprogramyouarewritingPythonknowsyouwantsomethingtobeastringwhenyouputeither(double-quotes)or(single-quotes)aroundthetextYousawthismanytimeswithyouruseofprintwhenyouputthetextyouwanttogoinsidethestringinsideoraftertheprinttoprintthestringStringscancontainanynumberofvariablesthatareinyourPythonscriptRememberthatavariableisanylineofcodewhereyousetaname=(equal)toavalueInthecodeforthisexercisetypes_of_people=10createsavariablenamedtypes_of_peopleandsetsit=(equal)to10Youcanputthatinanystringwithtypes_of_peopleYoualsoseethatIhavetouseaspecialtypeofstringtoldquoformatrdquoitrsquoscalledanldquof-stringrdquoandlookslikethisClickheretoviewcodeimage

fsomestuffhereavariable

fsomeotherstuffanothervar

Pythonalsohasanotherkindofformattingusingtheformat()syntaxwhichyouseeonline17YoursquollseemeusethatsometimeswhenIwanttoapplyaformattoanalready-createdstringsuchasinaloopWersquollcoverthatmorelaterWewillnowtypeinawholebunchofstringsvariablesandformatsandprintthemWewillalsopracticeusingshortabbreviatedvariablenamesProgrammerslovesavingtimeatyourexpensebyusingannoyinglyshortandcrypticvariablenamessoletrsquosgetyoustartedreadingandwritingthemearlyonClickheretoviewcodeimage

ex6py

1types_of_people=10

2x=fTherearetypes_of_peopletypesofpeople

3

4binary=binary

5do_not=dont

6y=fThosewhoknowbinaryandthosewhodo_not

7

8print(x)

9print(y)

10

11print(fIsaidx)

12print(fIalsosaidy)

13

14hilarious=False

15joke_evaluation=Isntthatjokesofunny

16

17print(joke_evaluationformat(hilarious))

18

19w=Thisistheleftsideof

20e=astringwitharightside

21

22print(w+e)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise6Session

$python36ex6py

Thereare10typesofpeople

Thosewhoknowbinaryandthosewhodont

IsaidThereare10typesofpeople

IalsosaidThosewhoknowbinaryandthosewhodont

IsntthatjokesofunnyFalse

Thisistheleftsideofastringwitharightside

StudyDrills1Gothroughthisprogramandwriteacommentaboveeachlineexplainingit

2FindalltheplaceswhereastringisputinsideastringTherearefourplaces

3AreyousurethereareonlyfourplacesHowdoyouknowMaybeIlikelying

4Explainwhyaddingthetwostringswandewith+makesalongerstring

BreakIt

YouarenowatapointwhereyoucantrytobreakyourcodetoseewhathappensThinkofthisasagametodevisethemostcleverwaytobreakthecodeYoucanalsofindthesimplestwaytobreakitOnceyoubreakthecodeyouthenneedtofixitIfyouhaveafriendthenthetwoofyoucantrytobreakeachotherrsquoscodeandfixitGiveyourfriendyourex6pyfilesotheycanbreaksomethingThenyoutrytofindtheirerrorandfixitHavefunwiththisandrememberthatifyouwrotethiscodeonceyoucandoitagainIfyoutakeyourdamagetoofaryoucanalwaystypeitinagainforextrapractice

CommonStudentQuestionsWhydoyouput(single-quotes)aroundsomestringsandnotothersMostlyitrsquosbecauseofstylebutIrsquolluseasingle-quoteinsideastringthathasdouble-quotesLookatlines6and15toseehowIrsquomdoingthat

Ifyouthoughtthejokewasfunnycouldyouwritehilarious=TrueYesandyoursquolllearnmoreaboutthesebooleanvaluesinExercise27

Exercise7MorePrinting

NowwearegoingtodoabunchofexerciseswhereyoujusttypecodeinandmakeitrunIwonrsquotbeexplainingthisexercisebecauseitismoreofthesameThepurposeistobuildupyourchopsSeeyouinafewexercisesanddonotskipDonotpasteClickheretoviewcodeimage

ex7py

1print(Maryhadalittlelamb)

2print(Itsfleecewaswhiteasformat(snow))

3print(AndeverywherethatMarywent)

4print(10)whatdthatdo

5

6end1=C

7end2=h

8end3=e

9end4=e

10end5=s

11end6=e

12end7=B

13end8=u

14end9=r

15end10=g

16end11=e

17end12=r

18

19watchthatcommaattheendtryremovingittoseewhat

happens

20print(end1+end2+end3+end4+end5+end6end=)

21print(end7+end8+end9+end10+end11+end12)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise7Session

$python36ex7py

Maryhadalittlelamb

Itsfleecewaswhiteassnow

AndeverywherethatMarywent

CheeseBurger

StudyDrillsForthesenextfewexercisesyouwillhavetheexactsameStudyDrills

1Gobackthroughandwriteacommentonwhateachlinedoes2Readeachonebackwardoroutloudtofindyourerrors3Fromnowonwhenyoumakemistakeswritedownonapieceofpaperwhatkindofmistakeyoumade

4Whenyougotothenextexerciselookatthemistakesyouhavemadeandtrynottomaketheminthisnewone

5RememberthateveryonemakesmistakesProgrammersarelikemagicianswhofooleveryoneintothinkingtheyareperfectandneverwrongbutitrsquosallanactTheymakemistakesallthetime

BreakItDidyouhavefunbreakingthecodeinExercise6FromnowonyoursquoregoingtobreakallthecodeyouwriteorafriendrsquoscodeIwonrsquothaveaBreakItsectionexplicitlyineveryexercisebutIwilldothisinalmosteveryvideoYourgoalistofindasmanydifferentwaystobreakyourcodeuntilyougettiredorexhaustallpossibilitiesInsomeexercisesImightpointoutaspecificcommonwaypeoplebreakthatexercisersquoscodebutotherwiseconsiderthisastandingordertoalwaysbreakit

CommonStudentQuestionsWhyareyouusingthevariablenamedsnowThatrsquosactuallynotavariableitisjustastringwiththewordsnowinitAvariablewouldnrsquothavethesingle-quotesaroundit

IsitnormaltowriteanEnglishcommentforeverylineofcodelikeyousaytodoinStudyDrill1Noyouwritecommentsonlytoexplaindifficult-to-understandcodeorwhyyoudidsomethingWhyisusuallymuchmoreimportantandthenyoutrytowritethecodesothatitexplainshowsomethingisbeingdoneonitsownHoweversometimesyouhavetowritesuchnastycodetosolveaproblemthatitdoesneedacommentoneverylineInthiscaseitrsquosstrictlyforyoutopracticetranslatingcodetoEnglish

CanIusesingle-quotesordouble-quotestomakeastringordo

theydodifferentthingsInPythoneitherwaytomakeastringisacceptablealthoughtypicallyyoursquollusesingle-quotesforanyshortstringslikeaorsnow

Exercise8PrintingPrinting

WewillnowseehowtodoamorecomplicatedformattingofastringThiscodelookscomplexbutifyoudoyourcommentsaboveeachlineandbreakeachthingdowntoitspartsyoursquollunderstanditClickheretoviewcodeimage

ex8py

1formatter=

2

3print(formatterformat(1234))

4print(formatterformat(onetwothreefour))

5print(formatterformat(TrueFalseFalseTrue))

6print(formatterformat(formatterformatterformatter

formatter))

7print(formatterformat(

8Tryyour

9Owntexthere

10Maybeapoem

11Orasongaboutfear

12))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise8Session

$python36ex8py

1234

onetwothreefour

TrueFalseFalseTrue

TryyourOwntexthereMaybeapoemOrasongaboutfearInthis

exerciseIrsquomusingsomethingcalledafunctiontoturntheformatter

variableintootherstringsWhenyouseemewrite

formatterformat()Irsquomtellingpythontodothefollowing1Take

theformatterstringdefinedonline1

2Callitsformatfunctionwhichissimilartotellingittodoacommandlinecommandnamedformat

3PasstoformatfourargumentswhichmatchupwiththefoursintheformattervariableThisislikepassingargumentstothecommandlinecommandformat

4TheresultofcallingformatonformatterisanewstringthathasthereplacedwiththefourvariablesThisiswhatprintisnowprintingout

ThatrsquosalotfortheeighthexercisesowhatIwantyoutodoisconsiderthisabrainteaserItrsquosalrightifyoudonrsquotreallyunderstandwhatrsquosgoingonbecausetherestofthebookwillslowlymakethisclearAtthispointtrytostudythisandseewhatrsquosgoingonthenmoveontothenextexercise

StudyDrillsDoyourcheckswritedownyourmistakesandtrynottomakethesamemistakesonthenextexerciseInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIhavetoputquotesaroundonebutnotaroundTrueorFalsePythonrecognizesTrueandFalseaskeywordsrepresentingtheconceptoftrueandfalseIfyouputquotesaroundthemthentheyareturnedintostringsandwonrsquotworkYoursquolllearnmoreabouthowtheseworkinExercise27

CanIuseIDLEtorunthisNoyoushouldlearntousethecommandlineItisessentialtolearningprogrammingandisagoodplacetostartifyouwanttolearnaboutprogrammingIDLEwillfailforyouwhenyougetfurtherinthebook

Exercise9PrintingPrintingPrinting

BynowyoushouldrealizethepatternforthisbookistousemorethanoneexercisetoteachyousomethingnewIstartwithcodethatyoumightnotunderstandthenmoreexercisesexplaintheconceptIfyoudonrsquotunderstandsomethingnowyouwilllaterasyoucompletemoreexercisesWritedownwhatyoudonrsquotunderstandandkeepgoingClickheretoviewcodeimage

ex9py

1Heressomenewstrangestuffremembertypeitexactly

2

3days=MonTueWedThuFriSatSun

4months=JannFebnMarnAprnMaynJunnJulnAug

5

6print(Herearethedaysdays)

7print(Herearethemonthsmonths)

8

9print(

10Theressomethinggoingonhere

11Withthethreedouble-quotes

12Wellbeabletotypeasmuchaswelike

13Even4linesifwewantor5or6

14)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise9Session

$python36ex9py

HerearethedaysMonTueWedThuFriSatSun

HerearethemonthsJan

Feb

Mar

Apr

May

Jun

Jul

Aug

Theressomethinggoingonhere

Withthethreedouble-quotes

Wellbeabletotypeasmuchaswelike

Even4linesifwewantor5or6

StudyDrillsCheckyourworkwritedownyourmistakestrynottomakethemonthenextexerciseAreyoubreakingyourcodeandthenfixingitInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIgetanerrorwhenIputspacesbetweenthethreedouble-quotesYouhavetotypethemlikeandnotmeaningwithnospacesbetweeneachone

WhatifIwantedtostartthemonthsonanewlineYousimplystartthestringwithnlikethisClickheretoviewcodeimagenJannFebnMarnAprnMaynJunnJulnAug

IsitbadthatmyerrorsarealwaysspellingmistakesMostprogrammingerrorsinthebeginning(andevenlater)aresimplespellingmistakestyposorgettingsimplethingsoutoforder

Exercise10WhatWasThat

InExercise9IthrewyousomenewstuffjusttokeepyouonyourtoesIshowedyoutwowaystomakeastringthatgoesacrossmultiplelinesInthefirstwayIputthecharactersn(backslashn)betweenthenamesofthemonthsThesetwocharactersputanewlinecharacterintothestringatthatpointThis(backslash)characterencodesdifficult-to-typecharactersintoastringTherearevariousescapesequencesavailablefordifferentcharactersyoumightwanttouseWersquolltryafewofthesesequencessoyoucanseewhatImeanAnimportantescapesequenceistoescapeasingle-quote()ordouble-quote()Imagineyouhaveastringthatusesdouble-quotesandyouwanttoputadouble-quoteinsidethestringIfyouwriteIunderstandjoethenPythonwillgetconfusedbecauseitwillthinkthedouble-quotesaroundunderstandactuallyendsthestringYouneedawaytotellPythonthatthedouble-quoteinsidethestringisnrsquotarealdouble-quoteTosolvethisproblemyouescapedouble-quotesandsingle-quotessoPythonknowstoincludetheminthestringHerersquosanexampleClickheretoviewcodeimage

Iam62tallescapedoublendashquoteinsidestring

Iam62tallescapesinglendashquoteinsidestringThesecond

wayisbyusingtriple-quoteswhichisjustandworkslikea

stringbutyoualsocanputasmanylinesoftextasyouwantuntil

youtypeagainWersquollalsoplaywiththese

Clickheretoviewcodeimage

ex10py

1tabby_cat=tImtabbedin

2persian_cat=Imsplitnonaline

3backslash_cat=Imacat

4

5fat_cat=

6Illdoalist

7tCatfood

8tFishies

9tCatnipntGrass

10

11

12print(tabby_cat)

13print(persian_cat)

14print(backslash_cat)

15print(fat_cat)

WhatYouShouldSeeLookforthetabcharactersthatyoumadeInthisexercisethespacingisimportanttogetright

$pythonex10py

Imtabbedin

Imsplit

onaline

Imacat

Illdoalist

Catfood

Fishies

Catnip

Grass

EscapeSequencesThisisalloftheescapesequencesPythonsupportsYoumaynotusemanyofthesebutmemorizetheirformatandwhattheydoanywayTrythemoutinsomestringstoseeifyoucanmakethemwork

StudyDrills1Memorizealltheescapesequencesbyputtingthemonflashcards2Use(triple-single-quote)insteadCanyouseewhyyoumightusethatinsteadof

3Combineescapesequencesandformatstringstocreateamorecomplexformat

CommonStudentQuestionsIstillhavenrsquotcompletelyfiguredoutthelastexerciseShouldIcontinueYeskeepgoingInsteadofstoppingtakenoteslistingthingsyoudonrsquotunderstandforeachexercisePeriodicallygothroughyournotesandseeifyoucanfigurethesethingsoutafteryoursquovecompletedmoreexercisesSometimesthoughyoumayneedtogobackafewexercisesanddothemagain

WhatmakesspecialcomparedtotheotheronesItrsquossimplythewayyouwouldwriteoutonebackslash()characterThinkaboutwhyyouwouldneedthis

WhenIwriteornitdoesnrsquotworkThatrsquosbecauseyouareusingaforward-slash()andnotabackslash()Theyaredifferentcharactersthatdoverydifferentthings

IdonrsquotgetStudyDrill3WhatdoyoumeanbyldquocombinerdquoescapesequencesandformatsOneconceptIneedyoutounderstandisthateachoftheseexercisescanbecombinedtosolveproblemsTakewhatyouknowaboutformatstringsandwritesomenewcodethatusesformatstringsandtheescapesequencesfromthisexercise

WhatrsquosbetterorItrsquosentirelybasedonstyleGowiththe(triple-single-quote)stylefornowbutbereadytouseeitherdependingonwhatfeelsbestorwhateveryoneelseisdoing

Exercise11AskingQuestions

NowitistimetopickupthepaceYouaredoingalotofprintingtogetyoufamiliarwithtypingsimplethingsbutthosesimplethingsarefairlyboringWhatwewanttodonowisgetdataintoyourprogramsThisisalittletrickybecauseyouhavetolearntodotwothingsthatmaynotmakesenserightawaybuttrustmeanddoitanywayItwillmakesenseinafewexercisesMostofwhatsoftwaredoesisthefollowing1Takessomekindofinputfromaperson

2Changesit3Printsoutsomethingtoshowhowitchanged

SofaryouhavebeenprintingstringsbutyouhavenrsquotbeenabletogetanyinputfromapersonYoumaynotevenknowwhatldquoinputrdquomeansbuttypethiscodeinanywayandmakeitexactlythesameInthenextexercisewersquolldomoretoexplaininputClickheretoviewcodeimage

ex11py

1print(Howoldareyouend=)

2age=input()

3print(Howtallareyouend=)

4height=input()

5print(Howmuchdoyouweighend=)

6weight=input()

7

8print(fSoyoureageoldheighttallandweight

heavy)

WarningWeputanend=attheendofeachprintlineThistellsprinttonotendthelinewithanewlinecharacterandgotothenextline

WhatYouShouldSeeClickheretoviewcodeimage

Exercise11Session

$python36ex11py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1GoonlineandfindoutwhatPythonrsquosinputdoes2CanyoufindotherwaystouseitTrysomeofthesamplesyoufind3Writeanotherldquoformrdquolikethistoasksomeotherquestions

CommonStudentQuestionsHowdoIgetanumberfromsomeonesoIcandomathThatrsquosalittleadvancedbuttryx=int(input())whichgetsthenumberasastringfrominput()thenconvertsittoanintegerusingint()

Iputmyheightintorawinputlikethisinput(62)butitdoesnrsquotworkDonrsquotputyourheightintheretypeitdirectlyintoyourTerminalFirstgobackandmakethecodeexactlylikemineNextrunthescriptandwhenitpausestypeyourheightinatyourkeyboardThatrsquosallthereistoit

Exercise12PromptingPeople

Whenyoutypedinput()youweretypingthe(and)characterswhichareparenthesischaractersThisissimilartowhenyouusedthemtodoaformatwithextravariablesasinfxyForinputyoucanalsoputinaprompttoshowtoapersonsoheknowswhattotypePutastringthatyouwantforthepromptinsidethe()sothatitlookslikethis

y=input(Name)

ThispromptstheuserwithldquoNamerdquoandputstheresultintothevariableyThisishowyouasksomeoneaquestionandgettheanswerThismeanswecancompletelyrewriteourpreviousexerciseusingjustinputtodoallthepromptingClickheretoviewcodeimage

ex12py

1age=input(Howoldareyou)

2height=input(Howtallareyou)

3weight=input(Howmuchdoyouweigh)

4

5print(fSoyoureageoldheighttallandweight

heavy)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise12Session

$python36ex12py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1InTerminalwhereyounormallyrunpython36torunyourscriptstypepydocinputReadwhatitsaysIfyoursquoreonWindowstry

python36-mpydocinputinstead2Getoutofpydocbytypingqtoquit3Lookonlineforwhatthepydoccommanddoes4UsepydoctoalsoreadaboutopenfileosandsysItrsquosalrightifyoudonotunderstandthosejustreadthroughandtakenotesaboutinterestingthings

CommonStudentQuestionsHowcomeIgetSyntaxErrorinvalidsyntaxwheneverIrunpydocYouarenrsquotrunningpydocfromthecommandlineyoursquoreprobablyrunningitfrominsidepython36Exitoutofpython36first

WhydoesmypydocnotpauselikeyoursdoesSometimesifthehelpdocumentisshortenoughtofitononescreenthenpydocwilljustprintit

WhenIrunpydocIgetmoreisnotrecognizedasaninternalSomeversionsofWindowsdonothavethatcommandwhichmeanspydocisbrokenforyouYoucanskipthisStudyDrillandjustsearchonlineforPythondocumentationwhenyouneedit

WhycanrsquotIdoprint(Howoldareyouinput())Youcanbutthentheresultofcallinginput()isneversavedtoavariableanditrsquollworkinastrangewayTrythisandthentrytoprintoutwhatyoutypeSeeifyoucandebugwhythisisnrsquotworking

Exercise13ParametersUnpackingVariables

Inthisexercisewewillcoveronemoreinputmethodyoucanusetopassvariablestoascript(scriptbeinganothernameforyourpyfiles)Youknowhowyoutypepython36ex13pytoruntheex13pyfileWelltheex13pypartofthecommandiscalledanargumentWhatwersquolldonowiswriteascriptthatalsoacceptsargumentsTypethisprogramandIrsquollexplainitindetailClickheretoviewcodeimage

ex13py

1fromsysimportargv

2readtheWYSSsectionforhowtorunthis

3scriptfirstsecondthird=argv

4

5print(Thescriptiscalledscript)

6print(Yourfirstvariableisfirst)

7print(Yoursecondvariableissecond)

8print(Yourthirdvariableisthird)

Online1wehavewhatrsquoscalledanimportThisishowyouaddfeaturestoyourscriptfromthePythonfeaturesetRatherthangiveyouallthefeaturesatoncePythonasksyoutosaywhatyouplantouseThiskeepsyourprogramssmallbutitalsoactsasdocumentationforotherprogrammerswhoreadyourcodelaterTheargvistheargumentvariableaverystandardnameinprogrammingthatyouwillfindusedinmanyotherlanguagesThisvariableholdstheargumentsyoupasstoyourPythonscriptwhenyourunitIntheexercisesyouwillgettoplaywiththismoreandseewhathappensLine3unpacksargvsothatratherthanholdingalltheargumentsitgetsassignedtofourvariablesyoucanworkwithscriptfirstsecondandthirdThismaylookstrangebutldquounpackrdquoisprobablythebestwordtodescribewhatitdoesItjustsaysldquoTakewhateverisinargvunpackitandassignittoallofthesevariablesontheleftinorderrdquoAfterthatwejustprintthemoutlikenormal

HoldUpFeaturesHaveAnotherName

Icallthemldquofeaturesrdquohere(theselittlethingsyouimporttomakeyourPythonprogramdomore)butnobodyelsecallsthemfeaturesIjustusedthatnamebecauseIneededtotrickyouintolearningwhattheyarewithoutjargonBeforeyoucancontinueyouneedtolearntheirrealnamemodulesFromnowonwewillbecallingtheseldquofeaturesrdquothatweimportmodulesIrsquollsaythingslikeldquoYouwanttoimportthesysmodulerdquoTheyarealsocalledldquolibrariesrdquobyotherprogrammersbutletrsquosjuststickwithmodules

WhatYouShouldSee

WarningPayattentionYouhavebeenrunningpythonscriptswithoutcommandlineargumentsIfyoutypeonlypython36ex13pyyouaredoingitwrongPaycloseattentiontohowIrunitThisappliesanytimeyouseeargvbeingused

Runtheprogramlikethis(andyoumustpassthreecommandlinearguments)Clickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd3rd

Thescriptiscalledex13py

Yourfirstvariableisfirst

Yoursecondvariableis2nd

Yourthirdvariableis3rd

ThisiswhatyoushouldseewhenyoudoafewdifferentrunswithdifferentargumentsClickheretoviewcodeimage

Exercise13Session

$python36ex13pystuffthingsthat

Thescriptiscalledex13py

Yourfirstvariableisstuff

Yoursecondvariableisthings

Yourthirdvariableisthat

$

$python36ex13pyappleorangegrapefruit

Thescriptiscalledex13py

Yourfirstvariableisapple

Yoursecondvariableisorange

Yourthirdvariableisgrapefruit

Youcanactuallyreplacefirst2ndand3rdwithanythreethingsyouwantIfyoudonotrunitcorrectlythenyouwillgetanerrorlikethisClickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd

Traceback(mostrecentcalllast)

Fileex13pyline3inltmodulegt

scriptfirstsecondthird=argv

ValueErrornotenoughvaluestounpack(expected4got3)

Thishappenswhenyoudonotputenoughargumentsonthecommandwhenyourunit(inthiscasejustfirst2nd)NoticethatwhenIrunitIgiveitfirst2ndwhichcausedittogiveanerroraboutldquoneedmorethan3valuestounpackrdquotellingyouthatyoudidnrsquotgiveitenoughparameters

StudyDrills1TrygivingfewerthanthreeargumentstoyourscriptSeethaterroryougetSeeifyoucanexplainit

2WriteascriptthathasfewerargumentsandonethathasmoreMakesureyougivetheunpackedvariablesgoodnames

3CombineinputwithargvtomakeascriptthatgetsmoreinputfromauserDonrsquotoverthinkitJustuseargvtogetsomethingandinputtogetsomethingelsefromtheuser

4RememberthatmodulesgiveyoufeaturesModulesModulesRememberthisbecausewersquollneeditlater

CommonStudentQuestionsWhenIrunitIgetValueErrorneedmorethan1valuetounpackRememberthatanimportantskillispayingattentiontodetailsIfyoulookattheWhatYouShouldSeesectionyouseethatIrunthescriptwithparametersonthecommandlineYoushouldreplicatehowIranitexactly

Whatrsquosthedifferencebetweenargvandinput()ThedifferencehastodowithwheretheuserisrequiredtogiveinputIftheygiveyourscriptinputsonthecommandlinethenyouuseargvIfyouwantthemtoinputusingthekeyboardwhilethescriptisrunningthenuseinput()

ArethecommandlineargumentsstringsYestheycomeinasstringsevenifyoutypednumbersonthecommandlineUseint()toconvertthemlikewithint(input())

HowdoyouusethecommandlineYoushouldhavelearnedtouseitveryquicklyandfluentlybynowbutifyouneedtolearnitatthisstagethenreadtheappendix

Icanrsquotcombineargvwithinput()DonrsquotoverthinkitJustslaptwolinesattheendofthisscriptthatuseinput()togetsomethingandthenprintitFromthatstartplayingwithmorewaystousebothinthesamescript

WhycanrsquotIdothisinput()=xBecausethatrsquosbackwardtohowitshouldworkDoitthewayIdoitanditrsquollwork

Exercise14PromptingandPassing

LetrsquosdooneexercisethatusesargvandinputtogethertoasktheusersomethingspecificYouwillneedthisforthenextexercisewhereyoulearntoreadandwritefilesInthisexercisewersquolluseinputslightlydifferentlybyhavingitprintasimplegtpromptThisissimilartogameslikeZorkorAdventureClickheretoviewcodeimage

ex14py

1fromsysimportargv

2

3scriptuser_name=argv

4prompt=gt

5

6print(fHiuser_nameImthescriptscript)

7print(Idliketoaskyouafewquestions)

8print(fDoyoulikemeuser_name)

9likes=input(prompt)

10

11print(fWheredoyouliveuser_name)

12lives=input(prompt)

13

14print(Whatkindofcomputerdoyouhave)

15computer=input(prompt)

16

17print(f

18Alrightsoyousaidlikesaboutlikingme

19YouliveinlivesNotsurewherethatis

20AndyouhaveacomputercomputerNice

21)Wemakeavariablepromptthatissettothepromptwe

wantandwegivethattoinputinsteadoftypingitoverandover

Nowifwewanttomakethepromptsomethingelsewejustchangeit

inthisonespotandrerunthescriptVeryhandy

WhatYouShouldSeeWhenyourunthisrememberthatyouhavetogivethescriptyournamefortheargvargumentsClickheretoviewcodeimage

Exercise14Session

$python36ex14pyzed

HizedImtheex14pyscript

Idliketoaskyouafewquestions

Doyoulikemezed

gtYes

Wheredoyoulivezed

gtSanFrancisco

Whatkindofcomputerdoyouhave

gtTandy1000

AlrightsoyousaidYesaboutlikingme

YouliveinSanFranciscoNotsurewherethatis

AndyouhaveaTandy1000computerNice

StudyDrills1FindoutwhatthegamesZorkandAdventurewereTrytofindcopiesandplaythem

2Changethepromptvariabletosomethingelseentirely3Addanotherargumentanduseitinyourscriptthesamewayyoudidinthepreviousexercisewithfirstsecond=ARGV

4MakesureyouunderstandhowIcombinedastylemultilinestringwiththeformatactivatorasthelastprint

CommonStudentQuestionsIgetSyntaxErrorinvalidsyntaxwhenIrunthisscriptAgainyouhavetorunitrightonthecommandlinenotinsidePythonIfyoutypepython36andthentrytotypepython36ex14pyZeditwillfailbecauseyouarerunningPythoninsidePythonCloseyourwindowandthenjusttypepython36ex14pyZed

IdonrsquotunderstandwhatyoumeanbychangingthepromptSeethevariableprompt=gtChangethattohaveadifferentvalueYouknowthisitrsquosjustastringandyoursquovedone13exercisesmakingthemsotakethetimetofigureitout

IgettheerrorValueErrorneedmorethan1valuetounpackRememberwhenIsaidyouneedtolookattheWhatYouShouldSeesectionandreplicatewhatIdidYouneedtodothesamethinghereandfocusonhowItypethecommandinandwhyIhaveacommandlineargument

HowcanIrunthisfromIDLEDonrsquotuseIDLECanIusedouble-quotesforthepromptvariableYoutotallycanGoaheadandtrythat

YouhaveaTandycomputerIdidwhenIwaslittleIgetNameErrornamepromptisnotdefinedwhenIrunitYoueitherspelledthenameofthepromptvariablewrongorforgotthatlineGobackandcompareeachlineofcodetominestartingatthebottomofthescriptandworkinguptothetopAnytimeyouseethiserroritmeansyouspelledsomethingwrongorforgottocreatethevariable

Exercise15ReadingFiles

YouknowhowtogetinputfromauserwithinputorargvNowyouwilllearnaboutreadingfromafileYoumayhavetoplaywiththisexercisethemosttounderstandwhatrsquosgoingonsodotheexercisecarefullyandrememberyourchecksWorkingwithfilesisaneasywaytoeraseyourworkifyouarenotcarefulThisexerciseinvolveswritingtwofilesOneistheusualex15pyfilethatyouwillrunbuttheotherisnamedex15_sampletxtThissecondfileisnrsquotascriptbutaplaintextfilewersquollbereadinginourscriptHerearethecontentsofthatfileClickheretoviewcodeimage

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

WhatwewanttodoisopenthatfileinourscriptandprintitoutHoweverwedonotwanttojusthardcodethenameex15_sampletxtintoourscriptldquoHardcodingrdquomeansputtingsomebitofinformationthatshouldcomefromtheuserasastringdirectlyinoursourcecodeThatrsquosbadbecausewewantittoloadotherfileslaterThesolutionistouseargvorinputtoasktheuserwhatfiletoopeninsteadofhardcodingthefilersquosnameClickheretoviewcodeimage

ex15py

1fromsysimportargv

2

3scriptfilename=argv

4

5txt=open(filename)

6

7print(fHeresyourfilefilename)

8print(txtread())

9

10print(Typethefilenameagain)

11file_again=input(gt)

12

13txt_again=open(file_again)

14

15print(txt_againread())Afewfancythingsaregoingoninthis

filesoletrsquosbreakitdownrealquicklybullLines1ndash3useargvto

getafilenameNextwehaveline5whereweuseanewcommand

openRightnowrunpydocopenandreadtheinstructionsNotice

howlikeyourownscriptsandinputittakesaparameterand

returnsavalueyoucansettoyourownvariableYoujustopeneda

file

bullLine7printsalittlemessagebutonline8wehavesomethingverynewandexcitingWecallafunctionontxtnamedreadWhatyougetbackfromopenisafileanditalsohascommandsyoucangiveitYougiveafileacommandbyusingthe(dotorperiod)thenameofthecommandandparametersjustlikewithopenandinputThedifferenceisthattxtread()saysldquoHeytxtDoyourreadcommandwithnoparametersrdquo

TheremainderofthefileismoreofthesamebutwersquollleavetheanalysistoyouintheStudyDrills

WhatYouShouldSee

WarningPayattentionIsaidpayattentionYouhavebeenrunningscriptswithjustthenameofthescriptbutnowthatyouareusingargvyouhavetoaddargumentsLookattheveryfirstlineoftheexamplebelowandyouwillseeIdopythonex15pyex15_sampletxttorunitSeetheextraargumentex15_sampletxtaftertheex15pyscriptnameIfyoudonottypethatyouwillgetanerrorsopayattention

Imadeafilecalledex15_sampletxtandranmyscriptClickheretoviewcodeimage

Exercise15Session

$python36ex15pyex15_sampletxt

Heresyourfileex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

Typethefilenameagain

gtex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

StudyDrillsThisisabigjumpsobesureyoudothisStudyDrillasbestyoucanbeforemovingon

1AboveeachlinecommentoutinEnglishwhatthatlinedoes2IfyouarenotsureasksomeoneforhelporsearchonlineManytimessearchingforldquopython36THINGrdquowillfindanswerstowhatthatTHINGdoesinPythonTrysearchingforldquopython36openrdquo

3IusedthewordldquocommandsrdquoherebutcommandsarealsocalledldquofunctionsrdquoandldquomethodsrdquoYouwilllearnaboutfunctionsandmethodslaterinthebook

4Getridoflines10ndash15whereyouuseinputandrunthescriptagain5UseonlyinputandtrythescriptthatwayWhyisonewayofgettingthefilenamebetterthananother

6Startpython36tostartthepython36shellanduseopenfromthepromptjustlikeinthisprogramNoticehowyoucanopenfilesandrunreadonthemfromwithinpython36

7Haveyourscriptalsocallclose()onthetxtandtxt_againvariablesItrsquosimportanttoclosefileswhenyouaredonewiththem

CommonStudentQuestionsDoestxt=open(filename)returnthecontentsofthefileNoitdoesnrsquotItactuallymakessomethingcalledafileobjectYoucanthinkofafilelikeanoldtapedrivethatyousawonmainframecomputersinthe1950sorevenlikeaDVDplayerfromtodayYoucanmovearoundinsidethemandthenldquoreadrdquothembuttheDVDplayerisnottheDVDthesamewaythefileobjectisnotthefilersquoscontents

IcanrsquottypecodeintoTerminalPowerShelllikeyousayinStudyDrill7Firstfromthecommandlinejusttypepython36andpressEnterNowyouareinpython36aswersquovedoneafewothertimesThenyoucantypeincodeandPythonwillrunitinlittlepiecesPlaywiththatTogetoutofittypequit()andhitEnter

WhyistherenoerrorwhenweopenthefiletwicePythonwillnotrestrictyoufromopeningafilemorethanonceandsometimesthisisnecessary

WhatdoesfromsysimportargvmeanFornowjustunderstandthatsysisapackageandthisphrasejustsaystogettheargvfeaturefromthatpackageYoursquolllearnmoreabouttheselater

Iputthenameofthefileinasscriptex15_sampletxt=argvbutitdoesnrsquotworkNothatrsquosnothowyoudoitMakethecodeexactlylikeminethenrunitfromthecommandlinetheexactsamewayIdoYoudonrsquotputthenamesoffilesinyouletPythonputthenamein

Exercise16ReadingandWritingFiles

IfyoudidtheStudyDrillsfromthelastexerciseyoushouldhaveseenallsortsofcommands(methodsfunctions)youcangivetofilesHerersquosthelistofcommandsIwantyoutorememberbullcloseClosesthefileLikeFile-gtSaveinyoureditor

bullreadReadsthecontentsofthefileYoucanassigntheresulttoavariable

bullreadlineReadsjustonelineofatextfilebulltruncateEmptiesthefileWatchoutifyoucareaboutthefilebullwrite(stuff)Writesldquostuffrdquotothefilebullseek(0)Movesthereadwritelocationtothebeginningofthefile

OnewaytorememberwhateachofthesedoesistothinkofavinylrecordcassettetapeVHStapeDVDorCDplayerIntheearlydaysofcomputersdatawasstoredoneachofthesekindsofmediasomanyofthefileoperationsstillresembleastoragesystemthatislinearTapeandDVDdrivesneedtoldquoseekrdquoaspecificspotandthenyoucanreadorwriteatthatspotTodaywehaveoperatingsystemsandstoragemediathatblurthelinesbetweenrandomaccessmemoryanddiskdrivesbutwestillusetheolderideaofalineartapewithareadwriteheadthatmustbemovedFornowthesearetheimportantcommandsyouneedtoknowSomeofthemtakeparametersbutwedonotreallycareaboutthatYouonlyneedtorememberthatwritetakesaparameterofastringyouwanttowritetothefileLetrsquosusesomeofthistomakeasimplelittletexteditorClickheretoviewcodeimage

ex16py

1fromsysimportargv

2

3scriptfilename=argv

4

5print(fWeregoingtoerasefilename)

6print(IfyoudontwantthathitCTRL-C(^C))

7print(IfyoudowantthathitRETURN)

8

9input()

10

11print(Openingthefile)

12target=open(filenamew)

13

14print(TruncatingthefileGoodbye)

15targettruncate()

16

17print(NowImgoingtoaskyouforthreelines)

18

19line1=input(line1)

20line2=input(line2)

21line3=input(line3)

22

23print(Imgoingtowritethesetothefile)

24

25targetwrite(line1)

26targetwrite(n)

27targetwrite(line2)

28targetwrite(n)

29targetwrite(line3)

30targetwrite(n)

31

32print(Andfinallywecloseit)

33targetclose()

ThatrsquosalargefileprobablythelargestyouhavetypedinSogoslowdoyourchecksandmakeitrunOnetrickistogetbitsofitrunningatatimeGetlines1ndash8runningthenfivemorethenafewmoreuntilitrsquosalldoneandrunning

WhatYouShouldSeeThereareactuallytwothingsyouwillseeFirsttheoutputofyournewscriptClickheretoviewcodeimage

Exercise16Session

$python36ex16pytesttxt

Weregoingtoerasetesttxt

IfyoudontwantthathitCTRL-C(^C)

IfyoudowantthathitRETURN

Openingthefile

TruncatingthefileGoodbye

NowImgoingtoaskyouforthreelines

line1Maryhadalittlelamb

line2Itsfleecewaswhiteassnow

line3Itwasalsotasty

Imgoingtowritethesetothefile

Andfinallywecloseit

Nowopenupthefileyoumade(inmycasetesttxt)inyoureditorandcheckitoutNeatright

StudyDrills1IfyoudonotunderstandthisgobackthroughandusethecommenttricktogetitsquaredawayinyourmindOnesimpleEnglishcommentaboveeachlinewillhelpyouunderstandoratleastletyouknowwhatyouneedtoresearchmore

2Writeascriptsimilartothelastexercisethatusesreadandargvtoreadthefileyoujustcreated

3TherersquostoomuchrepetitioninthisfileUsestringsformatsandescapestoprintoutline1line2andline3withjustonetargetwrite()commandinsteadofsix

4FindoutwhywehadtopassawasanextraparametertoopenHintopentriestobesafebymakingyouexplicitlysayyouwanttowriteafile

5Ifyouopenthefilewithwmodethendoyoureallyneedthetargettruncate()ReadthedocumentationforPythonrsquosopenfunctionandseeifthatrsquostrue

CommonStudentQuestionsIsthetruncate()necessarywiththewparameterSeeStudyDrillsnumber5

WhatdoeswmeanItrsquosreallyjustastringwithacharacterinitforthekindofmodeforthefileIfyouusewthenyoursquoresayingldquoopenthisfileinlsquowritersquomoderdquothusthewcharacterTherersquosalsorforldquoreadrdquoaforldquoappendrdquoandmodifiersonthese

WhatmodifierstothefilemodescanIuseThemostimportantonetoknowfornowisthe+modifiersoyoucandow+r+anda+Thiswillopenthefileinbothreadandwritemodeanddependingonthecharacterusepositionthefileindifferentways

Doesjustdoingopen(filename)openitinr(read)modeYesthatrsquosthedefaultfortheopen()function

Exercise17MoreFiles

NowletrsquosdoafewmorethingswithfilesWersquollwriteaPythonscripttocopyonefiletoanotherItrsquollbeveryshortbutwillgiveyouideasaboutotherthingsyoucandowithfilesClickheretoviewcodeimage

ex17py

1fromsysimportargv

2fromospathimportexists

3

4scriptfrom_fileto_file=argv

5

6print(fCopyingfromfrom_filetoto_file)

7

8wecoulddothesetwoononelinehow

9in_file=open(from_file)

10indata=in_fileread()

11

12print(fTheinputfileislen(indata)byteslong)

13

14print(fDoestheoutputfileexistexists(to_file))

15print(ReadyhitRETURNtocontinueCTRL-Ctoabort)

16input()

17

18out_file=open(to_filew)

19out_filewrite(indata)

20

21print(Alrightalldone)

22

23out_fileclose()

24in_fileclose()Youshouldimmediatelynoticethatweimport

anotherhandycommandnamedexistsThisreturnsTrueifafile

existsbasedonitsnameinastringasanargumentItreturns

FalseifnotWersquollbeusingthisfunctioninthesecondhalfofthis

booktodolotsofthingsbutrightnowyoushouldseehowyoucan

importit

Usingimportisawaytogettonsoffreecodeotherbetter(wellusually)programmershavewrittensoyoudonothavetowriteit

WhatYouShouldSee

JustlikeyourotherscriptsrunthisonewithtwoargumentsthefiletocopyfromandthefiletocopyittoIrsquomgoingtouseasimpletestfilenamedtesttxtClickheretoviewcodeimage

Exercise17Session

$firstmakeasamplefile

$echoThisisatestfilegttesttxt

$thenlookatit

$cattesttxt

Thisisatestfile

$nowrunourscriptonit

$python36ex17pytesttxtnew_filetxt

Copyingfromtesttxttonew_filetxt

Theinputfileis21byteslong

DoestheoutputfileexistFalse

ReadyhitRETURNtocontinueCTRL-Ctoabort

Alrightalldone

ItshouldworkwithanyfileTryabunchmoreandseewhathappensJustbecarefulyoudonotblastanimportantfile

WarningDidyouseethetrickIdidwithechotomakeafileandcattoshowthefileYoucanlearnhowtodothatintheAppendixldquoCommandLineCrashCourserdquo

StudyDrills1ThisscriptisreallyannoyingTherersquosnoneedtoaskyoubeforedoingthecopyanditprintstoomuchouttothescreenTrytomakethescriptmorefriendlytousebyremovingfeatures

2SeehowshortyoucanmakethescriptIcouldmakethisonelinelong3NoticeattheendoftheWhatYouShouldSeesectionIusedsomethingcalledcatItrsquosanoldcommandthatconcatenatesfilestogetherbutmostlyitrsquosjustaneasywaytoprintafiletothescreenTypemancattoreadaboutit

4Findoutwhyyouhadtowriteout_fileclose()inthecode

5GoreaduponPythonrsquosimportstatementandstartpython36totryitoutTryimportingsomethingsandseeifyoucangetitrightItrsquosalrightifyoudonot

CommonStudentQuestionsWhyisthewinquotesThatrsquosastringYoursquovebeenusingstringsforawhilenowMakesureyouknowwhatastringis

NowayyoucanmakethisonelineThatdependsonhowyoudefineonelineofcode

IsitnormaltofeellikethisexercisewasreallyhardYesitistotallynormalProgrammingmaynotldquoclickrdquoforyouuntilmaybeevenExercise36oritmightnotuntilyoufinishthebookandthenmakesomethingwithPythonEveryoneisdifferentsojustkeepgoingandkeepreviewingexercisesthatyouhadtroublewithuntilitclicksBepatient

Whatdoesthelen()functiondoItgetsthelengthofthestringthatyoupasstoitthenreturnsthatasanumberPlaywithit

WhenItrytomakethisscriptshorterIgetanerrorwhenIclosethefilesattheendYouprobablydidsomethinglikeindata=open(from_file)read()whichmeansyoudonrsquotneedtothendoin_fileclose()whenyoureachtheendofthescriptItshouldalreadybeclosedbyPythononcethatonelineruns

IgetaSyntaxEOLwhilescanningstringliteralerrorYouforgottoendastringproperlywithaquoteGolookatthatlineagain

Exercise18NamesVariablesCodeFunctions

BigtitlerightIamabouttointroduceyoutothefunctionDumdumdahEveryprogrammerwillgoonandonaboutfunctionsandallthedifferentideasabouthowtheyworkandwhattheydobutIwillgiveyouthesimplestexplanationyoucanuserightnowFunctionsdothreethings1Theynamepiecesofcodethewayvariablesnamestringsandnumbers

2Theytakeargumentsthewayyourscriptstakeargv3Using1and2theyletyoumakeyourownldquomini-scriptsrdquoorldquotinycommandsrdquo

YoucancreateafunctionbyusingtheworddefinPythonIrsquomgoingtohaveyoumakefourdifferentfunctionsthatworklikeyourscriptsandthenIrsquollshowyouhoweachoneisrelatedClickheretoviewcodeimage

ex18py

1thisoneislikeyourscriptswithargv

2defprint_two(args)

3arg1arg2=args

4print(farg1arg1arg2arg2)

5

6okthatargsisactuallypointlesswecanjustdothis

7defprint_two_again(arg1arg2)

8print(farg1arg1arg2arg2)

9

10thisjusttakesoneargument

11defprint_one(arg1)

12print(farg1arg1)

13

14thisonetakesnoarguments

15defprint_none()

16print(Igotnothin)

17

18

19print_two(ZedShaw)

20print_two_again(ZedShaw)

21print_one(First)

22print_none()Letrsquosbreakdownthefirstfunctionprint_two

whichisthemostsimilartowhatyoualreadyknowfrommaking

scripts1WetellPythonwewanttomakeafunctionusingdeffor

ldquodefinerdquo

2OnthesamelineasdefwegivethefunctionanameInthiscasewejustcalleditldquoprint_twordquobutitcouldalsobeldquopeanutsrdquoItdoesnrsquotmatterexceptthatyourfunctionshouldhaveashortnamethatsayswhatitdoes

3Wetellitwewantargs(asteriskargs)whichisalotlikeyourargvparameterbutforfunctionsThishastogoinsideparenthesestowork

4Weendthislinewitha(colon)andstartindenting5Afterthecolonallthelinesthatareindentedfourspaceswillbecomeattachedtoprint_twoOurfirstindentedlineisonethatunpackstheargumentsthesameaswithyourscripts

6Todemonstratehowitworksweprinttheseargumentsoutjustlikewewouldinascript

Theproblemwithprint_twoisthatitrsquosnottheeasiestwaytomakeafunctionInPythonwecanskipthewholeunpackingargumentsandjustusethenameswewantrightinsideparenthesesThatrsquoswhatprint_two_againdoesAfterthatyouhaveanexampleofhowyoumakeafunctionthattakesoneargumentinprint_oneFinallyyouhaveafunctionthathasnoargumentsinprint_none

WarningThisisveryimportantDonotgetdiscouragedrightnowifthisdoesnrsquotquitemakesenseWersquoregoingtodoafewexerciseslinkingfunctionstoyourscriptsandshowyouhowtomakemoreFornowjustkeepthinkingldquomini-scriptrdquowhenIsayldquofunctionrdquoandkeepplayingwiththem

WhatYouShouldSeeIfyourunex18pyyoushouldsee

Exercise18Session

$python36ex18py

arg1Zedarg2Shaw

arg1Zedarg2Shaw

arg1First

Igotnothin

RightawayyoucanseehowafunctionworksNoticethatyouusedyourfunctionsthewayyouusethingslikeexistsopenandothercommandsInfactIrsquovebeentrickingyoubecauseinPythonthosecommandsarejustfunctionsThismeansyoucanmakeyourowncommandsandusetheminyourscriptstoo

StudyDrillsCreateafunctionchecklistforlaterexercisesWritethesechecksonanindexcardandkeepitbyyouwhileyoucompletetherestoftheseexercisesoruntilyoufeelyoudonotneedtheindexcardanymore

1Didyoustartyourfunctiondefinitionwithdef2Doesyourfunctionnamehaveonlycharactersand_(underscore)characters

3Didyouputanopenparenthesisrightafterthefunctionname4Didyouputyourargumentsaftertheparenthesisseparatedbycommas5Didyoumakeeachargumentunique(meaningnoduplicatednames)6Didyouputacloseparenthesisandacolonafterthearguments7DidyouindentalllinesofcodeyouwantinthefunctionfourspacesNomorenoless

8Didyouldquoendrdquoyourfunctionbygoingbacktowritingwithnoindent(dedentingwecallit)

Whenyourun(ldquouserdquoorldquocallrdquo)afunctioncheckthesethings1Didyoucalluserunthisfunctionbytypingitsname

2Didyouputthe(characterafterthenametorunit3Didyouputthevaluesyouwantintotheparenthesesseparatedbycommas

4Didyouendthefunctioncallwitha)characterUsethesetwochecklistsontheremaininglessonsuntilyoudonotneedthemanymoreFinallyrepeatthisafewtimestoyourselfToldquorunrdquoldquocallrdquoorldquouserdquoafunctioneachmeansthesamething

CommonStudentQuestions

CommonStudentQuestionsWhatrsquosallowedforafunctionnameThesameasvariablenamesAnythingthatdoesnrsquotstartwithanumberandislettersnumbersandunderscoreswillwork

WhatdoestheinargsdoThattellsPythontotakealltheargumentstothefunctionandthenputtheminargsasalistItrsquoslikeargvthatyoursquovebeenusingbutforfunctionsItrsquosnotnormallyusedtoooftenunlessspecificallyneeded

ThisfeelsreallyboringandmonotonousThatrsquosgoodItmeansyoursquorestartingtogetbetterattypinginthecodeandunderstandingwhatitdoesTomakeitlessboringtakeeverythingItellyoutotypeinandthenbreakitonpurpose

Exercise19FunctionsandVariables

Functionsmayhavebeenamind-blowingamountofinformationbutdonotworryJustkeepdoingtheseexercisesandgoingthroughyourchecklistfromthelastexerciseandyouwilleventuallygetitThereisonetinypointthatyoumightnothaverealizedwhichwersquollreinforcerightnowThevariablesinyourfunctionarenotconnectedtothevariablesinyourscriptHerersquosanexercisetogetyouthinkingaboutthisClickheretoviewcodeimage

ex19py

1defcheese_and_crackers(cheese_countboxes_of_crackers)

2print(fYouhavecheese_countcheeses)

3print(fYouhaveboxes_of_crackersboxesofcrackers)

4print(Manthatsenoughforaparty)

5print(Getablanketn)

6

7

8print(Wecanjustgivethefunctionnumbersdirectly)

9cheese_and_crackers(2030)

10

11

12print(ORwecanusevariablesfromourscript)

13amount_of_cheese=10

14amount_of_crackers=50

15

16cheese_and_crackers(amount_of_cheeseamount_of_crackers)

17

18

19print(Wecanevendomathinsidetoo)

20cheese_and_crackers(10+205+6)

21

22

23print(Andwecancombinethetwovariablesandmath)

24cheese_and_crackers(amount_of_cheese+100amount_of_crackers

+1000)Thisshowsallthedifferentwayswersquoreabletogiveour

functioncheese_and_crackersthevaluesitneedstoprintthemWe

cangiveitstraightnumbersWecangiveitvariablesWecangive

itmathWecanevencombinemathandvariables

Inawaytheargumentstoafunctionarekindoflikeour=characterwhenwemakeavariableInfactifyoucanuse=tonamesomethingyoucanusually

passittoafunctionasanargument

WhatYouShouldSeeYoushouldstudytheoutputofthisscriptandcompareitwithwhatyouthinkyoushouldgetforeachoftheexamplesinthescriptClickheretoviewcodeimage

Exercise19Session

$python36ex19py

Wecanjustgivethefunctionnumbersdirectly

Youhave20cheeses

Youhave30boxesofcrackers

Manthatsenoughforaparty

Getablanket

ORwecanusevariablesfromourscript

Youhave10cheeses

Youhave50boxesofcrackers

Manthatsenoughforaparty

Getablanket

Wecanevendomathinsidetoo

Youhave30cheeses

Youhave11boxesofcrackers

Manthatsenoughforaparty

Getablanket

Andwecancombinethetwovariablesandmath

Youhave110cheeses

Youhave1050boxesofcrackers

Manthatsenoughforaparty

Getablanket

StudyDrills1GobackthroughthescriptandtypeacommentaboveeachlineexplaininginEnglishwhatitdoes

2Startatthebottomandreadeachlinebackwardsayingalltheimportantcharacters

3Writeatleastonemorefunctionofyourowndesignandrunit10differentways

CommonStudentQuestions

Howcantherepossiblybe10differentwaystorunafunctionBelieveitornottherersquosatheoreticallyinfinitenumberofwaystocallanyfunctionSeehowcreativeyoucangetwithfunctionsvariablesandinputfromauser

IsthereawaytoanalyzewhatthisfunctionisdoingsoIcanunderstanditbetterTherearemanydifferentwaysbuttryputtinganEnglishcommentaboveeachlinedescribingwhatthelinedoesAnothertrickistoreadthecodeoutloudYetanotheristoprintthecodeoutanddrawonthepaperwithpicturesandcommentsshowingwhatrsquosgoingon

WhatifIwanttoasktheuserforthenumbersofcheeseandcrackersYouneedtouseint()toconvertwhatyougetfrominput()

Doesmakingthevariableamount_of_cheesechangethevariablecheese_countinthefunctionNothosevariablesareseparateandliveoutsidethefunctionTheyarethenpassedtothefunctionandtemporaryversionsaremadejustforthefunctionrsquosrunWhenthefunctionexitsthesetemporaryvariablesgoawayandeverythingkeepsworkingKeepgoinginthebookandthisshouldbecomeclearer

Isitbadtohaveglobalvariables(likeamount_of_cheese)withthesamenameasfunctionvariablesYessincethenyoursquorenotquitesurewhichoneyoursquoretalkingaboutButsometimesnecessitymeansyouhavetousethesamenameoryoumightdoitonaccidentJustavoiditwheneveryoucan

IstherealimittothenumberofargumentsafunctioncanhaveItdependsontheversionofPythonandthecomputeryoursquoreonbutitisfairlylargeThepracticallimitthoughisaboutfiveargumentsbeforethefunctionbecomesannoyingtouse

CanyoucallafunctionwithinafunctionYesyoursquollmakeagamethatdoesthislaterinthebook

Exercise20FunctionsandFiles

RememberyourchecklistforfunctionsthendothisexercisepayingcloseattentiontohowfunctionsandfilescanworktogethertomakeusefulstuffClickheretoviewcodeimage

ex20py

1fromsysimportargv

2

3scriptinput_file=argv

4

5defprint_all(f)

6print(fread())

7

8defrewind(f)

9fseek(0)

10

11defprint_a_line(line_countf)

12print(line_countfreadline())

13

14current_file=open(input_file)

15

16print(Firstletsprintthewholefilen)

17

18print_all(current_file)

19

20print(Nowletsrewindkindoflikeatape)

21

22rewind(current_file)

23

24print(Letsprintthreelines)

25

26current_line=1

27print_a_line(current_linecurrent_file)

28

29current_line=current_line+1

30print_a_line(current_linecurrent_file)

31

32current_line=current_line+1

33print_a_line(current_linecurrent_file)Paycloseattentionto

howwepassinthecurrentlinenumbereachtimewerunprint_a_line

WhatYouShouldSee

Clickheretoviewcodeimage

Exercise20Session

$python36ex20pytesttxt

Firstletsprintthewholefile

Thisisline1

Thisisline2

Thisisline3

Nowletsrewindkindoflikeatape

Letsprintthreelines

1Thisisline1

2Thisisline2

3Thisisline3

StudyDrills1WriteanEnglishcommentforeachlinetounderstandwhatthatlinedoes2Eachtimeprint_a_lineisrunyouarepassinginavariablecurrent_lineWriteoutwhatcurrent_lineisequaltooneachfunctioncallandtracehowitbecomesline_countinprint_a_line

3Findeachplaceafunctionisusedandcheckitsdeftomakesurethatyouaregivingittherightarguments

4ResearchonlinewhattheseekfunctionforfiledoesTrypydocfileandseeifyoucanfigureitoutfromthereThentrypydocfileseektoseewhatseekdoes

5Researchtheshorthandnotation+=andrewritethescripttouse+=instead

CommonStudentQuestionsWhatisfintheprint_allandotherfunctionsThefisavariablejustlikeyouhadinotherfunctionsinExercise18exceptthistimeitrsquosafileAfileinPythoniskindoflikeanoldtapedriveonamainframeormaybeaDVDplayerIthasaldquoreadheadrdquoandyoucanldquoseekrdquothisreadheadaroundthefiletopositionsthenworkwithitthereEachtimeyoudofseek(0)yoursquoremovingtothe

startofthefileEachtimeyoudofreadline()yoursquorereadingalinefromthefileandmovingthereadheadtorightafterthenthatendsthatlineThiswillbeexplainedmoreasyougoon

Whydoesseek(0)notsetthecurrent_lineto0Firsttheseek()functionisdealinginbytesnotlinesThecodeseek(0)movesthefiletothe0byte(firstbyte)inthefileSecondcurrent_lineisjustavariableandhasnorealconnectiontothefileatallWearemanuallyincrementingit

Whatis+=YouknowhowinEnglishIcanrewriteldquoitisrdquoasldquoitrsquosrdquoOrIcanrewriteldquoyouarerdquoasldquoyoursquorerdquoInEnglishthisiscalledacontractionandthisiskindoflikeacontractionforthetwooperations=and+Thatmeansx=x+yisthesameasx+=y

Howdoesreadline()knowwhereeachlineisInsidereadline()iscodethatscanseachbyteofthefileuntilitfindsancharacterthenstopsreadingthefiletoreturnwhatitfoundsofarThefilefisresponsibleformaintainingthecurrentpositioninthefileaftereachreadline()callsothatitwillkeepreadingeachline

WhyarethereemptylinesbetweenthelinesinthefileThereadline()functionreturnsthenthatrsquosinthefileattheendofthatlineAddaend=attheendofyourprintfunctioncallstoavoidaddingdoublentoeveryline

Exercise21FunctionsCanReturnSomething

Youhavebeenusingthe=charactertonamevariablesandsetthemtonumbersorstringsWersquorenowgoingtoblowyourmindagainbyshowingyouhowtouse=andanewPythonwordreturntosetvariablestobeavaluefromafunctionTherewillbeonethingtopaycloseattentiontobutfirsttypethisinClickheretoviewcodeimage

ex21py

1defadd(ab)

2print(fADDINGa+b)

3returna+b

4

5defsubtract(ab)

6print(fSUBTRACTINGa-b)

7returna-b

8

9defmultiply(ab)

10print(fMULTIPLYINGab)

11returnab

12

13defdivide(ab)

14print(fDIVIDINGab)

15returnab

16

17

18print(Letsdosomemathwithjustfunctions)

19

20age=add(305)

21height=subtract(784)

22weight=multiply(902)

23iq=divide(1002)

24

25print(fAgeageHeightheightWeightweightIQ

iq)

26

27

28Apuzzlefortheextracredittypeitinanyway

29print(Hereisapuzzle)

30

31what=add(agesubtract(heightmultiply(weightdivide(iq

2))))

32

33print(ThatbecomeswhatCanyoudoitbyhand)Weare

nowdoingourownmathfunctionsforaddsubtractmultiplyand

divideTheimportantthingtonoticeisthelastlinewherewesay

returna+b(inadd)Whatthisdoesisthefollowing1Our

functioniscalledwithtwoargumentsaandb

2WeprintoutwhatourfunctionisdoinginthiscaseldquoADDINGrdquo3WetellPythontodosomethingkindofbackwardwereturntheadditionofa+bYoumightsaythisasldquoIaddaandbthenreturnthemrdquo

4PythonaddsthetwonumbersThenwhenthefunctionendsanylinethatrunsitwillbeabletoassignthisa+bresulttoavariable

AswithmanyotherthingsinthisbookyoushouldtakethisrealslowbreakitdownandtrytotracewhatrsquosgoingonTohelpthereisextracredittosolveapuzzleandlearnsomethingcool

WhatYouShouldSeeClickheretoviewcodeimage

Exercise21Session

$python36ex21py

Letsdosomemathwithjustfunctions

ADDING30+5

SUBTRACTING78-4

MULTIPLYING902

DIVIDING1002

Age35Height74Weight180IQ500

Hereisapuzzle

DIVIDING5002

MULTIPLYING180250

SUBTRACTING74-45000

ADDING35+-44260

Thatbecomes-43910Canyoudoitbyhand

StudyDrills1IfyouarenrsquotreallysurewhatreturndoestrywritingafewofyourownfunctionsandhavethemreturnsomevaluesYoucanreturnanythingthatyoucanputtotherightofan=

2AttheendofthescriptisapuzzleIrsquomtakingthereturnvalueofonefunctionandusingitastheargumentofanotherfunctionIrsquomdoingthisinachainsothatIrsquomkindofcreatingaformulausingthefunctionsItlooks

reallyweirdbutifyourunthescriptyoucanseetheresultsWhatyoushoulddoistrytofigureoutthenormalformulathatwouldrecreatethissamesetofoperations

3OnceyouhavetheformulaworkedoutforthepuzzlegetinthereandseewhathappenswhenyoumodifythepartsofthefunctionsTrytochangeitonpurposetomakeanothervalue

4DotheinverseWriteasimpleformulaandusethefunctionsinthesamewaytocalculateit

ThisexercisemightreallywhackyourbrainoutbuttakeitslowandeasyandtreatitlikealittlegameFiguringoutpuzzleslikethisiswhatmakesprogrammingfunsoIrsquollbegivingyoumorelittleproblemslikethisaswego

CommonStudentQuestionsWhydoesPythonprinttheformulaorthefunctionsldquobackwardrdquoItrsquosnotreallybackwarditrsquosldquoinsideoutrdquoWhenyoustartbreakingdownthefunctionintoseparateformulasandfunctioncallsyoursquollseehowitworksTrytounderstandwhatImeanbyldquoinsideoutrdquoratherthanldquobackwardrdquo

HowcanIuseinput()toentermyownvaluesRememberint(input())Theproblemwiththatisthenyoucanrsquotenterfloatingpointsoalsotryusingfloat(input())instead

WhatdoyoumeanbyldquowriteoutaformulardquoTry24+34100-1023asastartConvertthattousethefunctionsNowcomeupwithyourownsimilarmathequationandusevariablessoitrsquosmorelikeaformula

Exercise22WhatDoYouKnowSoFar

TherewonrsquotbeanycodeinthisexerciseorthenextonesotherersquosnoWhatYouShouldSeeorStudyDrillssectionsInfactthisexerciseislikeonegiantStudyDrillsIrsquomgoingtohaveyoudoareviewofwhatyouhavelearnedsofarFirstgobackthrougheveryexerciseyouhavedonesofarandwritedowneverywordandsymbol(anothernameforldquocharacterrdquo)thatyouhaveusedMakesureyourlistofsymbolsiscompleteNexttoeachwordorsymbolwriteitsnameandwhatitdoesIfyoucanrsquotfindanameforasymbolinthisbookthenlookforitonlineIfyoudonotknowwhatawordorsymboldoesthenreadaboutitagainandtryusingitinsomecodeYoumayrunintoafewthingsyoucanrsquotfindoutorknowsojustkeepthoseonthelistandbereadytolookthemupwhenyoufindthemOnceyouhaveyourlistspendafewdaysrewritingthelistanddouble-checkingthatitrsquoscorrectThismaygetboringbutpushthroughandreallynailitdownOnceyouhavememorizedthelistandwhattheydothenstepitupbywritingouttablesofsymbolstheirnamesandwhattheydofrommemoryIfyouhitsomeyoucanrsquotrecallfrommemorygobackandmemorizethemagain

WarningThemostimportantthingwhendoingthisexerciseisldquoThereisnofailureonlytryingrdquo

WhatYouAreLearningItrsquosimportantwhenyouaredoingaboringmindlessmemorizationexerciselikethistoknowwhyIthelpsyoufocusonagoalandknowthepurposeofallyoureffortsInthisexerciseyouarelearningthenamesofsymbolssothatyoucanreadsourcecodemoreeasilyItrsquossimilartolearningthealphabetandbasicwordsofEnglishexceptthisPythonalphabethasextrasymbolsyoumightnotknowJusttakeitslowanddonothurtyourbrainItrsquosbesttotake15minutesatatimewithyourlistandthentakeabreakGivingyourbrainarestwillhelpyoulearnfasterwithlessfrustration

Exercise23StringsBytesandCharacterEncodings

TodothisexerciseyoursquollneedtodownloadatextfilethatIrsquovewrittennamedlanguagestxt(httpslearnpythonthehardwayorgpython3languagestxt)Thisfilewascreatedwithalistofhumanlanguagestodemonstrateafewinterestingconcepts

1HowmoderncomputersstorehumanlanguagesfordisplayandprocessingandhowPython3callsthisstrings

2HowyoumustldquoencoderdquoandldquodecoderdquoPythonrsquosstringsintoatypecalledbytes

3Howtohandleerrorsinyourstringandbytehandling4Howtoreadcodeandfindoutwhatitmeansevenifyoursquoveneverseenitbefore

InadditiontothatyoursquollalsogetabriefglimpseofthePython3if-statementandlistsforprocessingalistofthingsYoudonrsquothavetomasterthiscodeorunderstandtheseconceptsrightawayYoursquollgetplentyofpracticeinlaterexercisesFornowyourjobistogetatasteofthefutureandlearnthefourtopicsintheprecedinglist

WarningThisexerciseishardTherersquosalotofinformationinitthatyouneedtounderstandanditrsquosinformationthatgoesdeepintocomputersThisexerciseiscomplexbecausePythonrsquosstringsarecomplexanddifficulttouseIrecommendyoutakethisexercisepainfullyslowWritedowneverywordyoudonrsquotunderstandandlookituporresearchitTakeaparagraphatatimeifyoumustYoucancontinuewithotherexerciseswhileyoustudythisonesodonrsquotgetstuckhereJustchipawayatitforaslongasittakes

InitialResearchIrsquomgoingtoteachyouhowtoresearchapieceofcodetoexposeitssecretsYoursquollneedthelanguagestxtfileforthiscodetoworksomakesureyoudownloaditfirstThelanguagestxtfilesimplycontainsalistofhumanlanguagenamesthatareencodedinUTF-8Clickheretoviewcodeimage

ex23py

1importsys

2scriptencodingerror=sysargv

3

4

5defmain(language_fileencodingerrors)

6line=language_filereadline()

7

8ifline

9print_line(lineencodingerrors)

10returnmain(language_fileencodingerrors)

11

12

13defprint_line(lineencodingerrors)

14next_lang=linestrip()

15raw_bytes=next_langencode(encodingerrors=errors)

16cooked_string=raw_bytesdecode(encodingerrors=errors)

17

18print(raw_byteslt===gtcooked_string)

19

20

21languages=open(languagestxtencoding=utf-8)

22

23main(languagesencodingerror)

SimplywritedownalistofeachthingyoursquoveneverseenbeforeTheremaybequiteafewthingsthatarenewsoscanthefileafewtimesOnceyouhavethatyoursquollwanttorunthisPythonscripttoplaywithitHerearesomeexamplecommandsIusedtotestit

WarningYoursquollnoticeIrsquomusingimagesheretoshowyouwhatyoushouldseeAfterextensivetestingitturnsoutthatsomanypeoplehave

seeAfterextensivetestingitturnsoutthatsomanypeoplehavetheircomputersconfiguredtonotdisplayUTF-8thatIhadtouseimagessoyoursquollknowwhattoexpectEvenmyowntypesettingsystem(LaTeX)couldnrsquothandletheseencodingsforcingmetouseimagesinsteadIfyoudonrsquotseethisthenyourTerminalismostlikelynotabletodisplayUTF-8andyoushouldtrytofixthat

Theseexamplesusetheutf-8utf-16andbig5encodingstodemonstratetheconversionandthetypesoferrorsyoucangetEachofthesenamesarecalledaldquocodecrdquoinPython3butyouusetheparameterldquoencodingrdquoAttheendofthisexercisetherersquosalistoftheavailableencodingsifyouwanttotrymoreIrsquollcoverwhatallofthisoutputmeansshortlyYoursquoreonlytryingtogetanideaofhowthisworkssowecantalkaboutitAfteryoursquoverunitafewtimesgothroughyourlistofsymbolsandmakeaguessastowhattheydoWhenyoursquovewrittendownyourguessestrylookingthesymbolsuponlinetoseeifyoucanconfirmyourhypothesesDonrsquotworryifyouhavenoideahowtosearchforthemJustgiveitatry

SwitchesConventionsandEncodingsBeforeIcangetintowhatthiscodemeansyouneedtolearnsomebasicsabouthowdataisstoredinacomputerModerncomputersareincrediblycomplexbutattheircorestheyarelikeahugearrayoflightswitchesComputersuseelectricitytoflipswitchesonoroffTheseswitchescanrepresent1foronor0foroffIntheolddaystherewereallkindsofweirdcomputersthatdidmorethanjust1or0butthesedaysitrsquosjust1sand0sOnerepresentsenergyelectricityonpowersubstanceZerorepresentsoffdonegonepowerdownthelackofenergyWecallthese1sand0sldquobitsrdquoNowacomputerthatonlyletsyouworkwith1and0wouldbebothhorriblyinefficientandincrediblyannoyingComputerstakethese1sand0sandusethemtoencodelargernumbersAtthesmallendacomputerwilluse8ofthese1sand0stoencode256numbers(0-255)WhatdoesldquoencoderdquomeanthoughItrsquosnothingmorethananagreed-uponstandardforhowasequenceofbitsshouldrepresentanumberItrsquosaconventionhumanspickedorstumbledonthatsaysthat00000000wouldbe011111111wouldbe255and00001111wouldbe15TherewereevenhugewarsintheearlyhistoryofcomputersonnothingmorethantheorderofthesebitsbecausetheyweresimplyconventionsweallhadtoagreeonTodaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryone

Todaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryonehadtheirownconventionforabytesoyoursquollstillrunintopeoplewhothinkthatthistermshouldbeflexibleandhandlesequencesof9bits7bitsor6bitsbutnowwejustsayitrsquos8bitsThatrsquosourconventionandthatconventiondefinesourencodingforabyteTherearefutherconventionsforencodinglargenumbersusing163264andevenmorebitsifyougetintoreallybigmathTherersquosentirestandardsgroupswhodonothingbutargueabouttheseconventionsthenimplementthemasencodingsthateventuallyturnswitchesonandoffOnceyouhavebytesyoucanstarttostoreanddisplaytextbydecidingonanotherconventionforhowanumbermapstoaletterIntheearlydaysofcomputingthereweremanyconventionsthatmapped8or7bits(orlessormore)ontolistsofcharacterskeptinsideacomputerThemostpopularconventionendedupbeingAmericanStandardCodeforInformationInterchangeorASCIIThisstandardmapsanumbertoaletterThenumber90isZwhichinbitsis1011010whichgetsmappedtotheASCIItableinsidethecomputerYoucantrythisoutinPythonrightnow

gtgtgt0b1011010

90

gtgtgtord(Z)

90

gtgtgtchr(90)

Z

gtgtgt

FirstIwritethenumber90inbinarythenIgetthenumberbasedontheletterZthenIconvertthenumbertotheletterZDonrsquotworryaboutneedingtorememberthisthoughIthinkIrsquovehadtodoittwicetheentiretimeIrsquoveusedPythonOncewehavetheASCIIconventionforencodingacharacterusing8bits(abyte)wecanthenldquostringrdquothemtogethertomakeawordIfIwanttowritemynameldquoZedAShawrdquoIjustuseasequenceofbytes[90101100326546328310497119]MostoftheearlytextincomputerswasnothingmorethansequencesofbytesstoredinmemorythatacomputerusedtodisplaytexttoapersonAgainthisisjustasequenceofconventionsthatturnedswitchesonandoffTheproblemwithASCIIisthatitonlyencodesEnglishandmaybeafewothersimilarlanguagesRememberthatabytecanhold256numbers(0-255or

00000000-11111111)Turnsouttherersquosalotmorecharactersthan256usedthroughouttheworldrsquoslanguagesDifferentcountriescreatedtheirownencodingconventionsfortheirlanguagesandthatmostlyworkedbutmanyencodingscouldonlyhandleonelanguageThatmeantifyouwanttoputthetitleofanAmericanEnglishbookinthemiddleofaThaisentenceyouwerekindofintroubleYoursquodneedoneencodingforThaiandoneforEnglishTosolvethisproblemagroupofpeoplecreatedUnicodeItsoundslikeldquoencoderdquoanditismeanttobealdquouniversalencodingrdquoofallhumanlanguagesThesolutionUnicodeprovidesisliketheASCIItablebutitrsquoshugebycomparisonYoucanuse32bitstoencodeaUnicodecharacterandthatismorecharactersthanwecouldpossiblyfindA32-bitnumbermeanswecanstore4294967295characters(2^32)whichisenoughspaceforeverypossiblehumanlanguageandprobablyalotofalienonestooRightnowweusetheextraspaceforimportantthingslikepoopandsmileemojisWenowhaveaconventionforencodinganycharacterswewantbut32bitsis4bytes(328==4)whichmeansthereissomuchwastedspaceinmosttextwewanttoencodeWecanalsouse16bits(2bytes)butstilltherersquosgoingtobewastedspaceinmosttextThesolutionistouseacleverconventiontoencodemostcommoncharactersusing8bitsandthenldquoescaperdquointolargernumberswhenweneedtoencodemorecharactersThatmeanswehaveonemoreconventionthatisnothingmorethanacompressionencodingmakingitpossibleformostcommoncharacterstouse8bitsandthenescapeoutinto16or32bitsasneededTheconventionforencodingtextinPythoniscalledldquoUTF-8rdquowhichmeansldquoUnicodeTransformationFormat8BitsrdquoItisaconventionforencodingUnicodecharactersintosequencesofbyteswhicharesequencesofbitswhichturnsequencesofswitchesonandoffYoucanalsouseotherconventions(encodings)butUTF-8isthecurrentstandard

DisectingtheOutputWecannowlookattheoutputofthecommandsshownpreviouslyLetrsquostakejustthatfirstcommandandthefirstfewlinesofoutput

Theex23pyscriptistakingbyteswritteninsidetheb(bytestring)andconvertingthemtotheUTF-8(orother)encodingyouspecifiedOntheleftisthenumbersforeachbyteoftheUTF-8(showninhexadecimal)andtherighthasthecharacteroutputasactualUTF-8Thewaytothinkofthisistheleftsideoflt===gtisthePythonnumericalbytesortheldquorawrdquobytesPythonusestostorethestringYouspecifythiswithbtotellPythonthisisbytesTheserawbytesarethendisplayedldquocookedrdquoontherightsoyoucanseetherealcharactersinyourTerminal

DisectingtheCodeWehaveanunderstandingofstringsandbytesequencesInPythonastringisaUTF-8encodedsequenceofcharactersfordisplayingorworkingwithtextThebytesarethentheldquorawrdquosequenceofbytesthatPythonusestostorethisUTF-8stringandstartwithabtotellPythonyouareworkingwithrawbytesThisisallbasedonconventionsforhowPythonwantstoworkwithtextHerersquosaPythonsessionshowingmeencodingstringsanddecodingbytes

Allyouneedtorememberisifyouhaverawbytesthenyoumustusedecode()togetthestringRawbyteshavenoconventiontothemTheyarejustsequencesofbyteswithnomeaningotherthannumberssoyoumusttellPythontoldquodecodethisintoaUTFstringrdquoIfyouhaveastringandwanttosenditstoreitshareitordosomeotheroperationthenusuallyitrsquollworkbutsometimesPythonwillthrowupanerrorsayingitdoesnrsquotknowhowtoldquoencoderdquoitAgainPythonknowsitsinternalconventionbutithasnoideawhatconventionyouneedInthatcaseyoumustuseencode()togetthebytesyouneedThewaytorememberthis(eventhoughIlookitupalmosteverytime)istorememberthemnemonicDBESwhichstandsforDecodeBytesEncodeStringsIsayldquodeebessrdquoinmyheadwhenIhavetoconvertbytesandstringsWhenyouhavebytesandneedastringdecodebytesWhenyouhaveastringandneedbytesencodestringsWiththatinmindletrsquosbreakdownthecodeinex23pyline-by-line1ndash2Istartwiththeusualcommandlineargumenthandlingthatyoualready

know5IstartthemainmeatofthiscodeinafunctionconvenientlycalledmainThiswillbecalledattheendofthisscripttogetthingsgoing

6ThefirstthingthisfunctiondoesisreadonelinefromthelanguagesfileitisgivenYouhavedonethisbeforesonothingnewhereJustreadlineasbeforewhendealingwithtextfiles

8IusesomethingnewYouwilllearnaboutthisinthesecondhalfofthebooksoconsiderthisateaserofinterestingthingstocomeThisisanif-statementanditletsyoumakedecisionsinyourPythoncodeYoucantestthetruthofavariableandbasedonthattruthrunapieceofcodeornotrunitInthiscaseIrsquomtestingwhetherlinehassomethinginitThereadlinefunctionwillreturnanemptystringwhenitreachestheendofthefileandiflinesimplytestsforthisemptystringAslongasreadlinegivesussomethingthiswillbetrueandthecodeunder(indentedinlines9ndash10)willrunWhenthisisfalsePythonwillskiplines9ndash10

9IcallaseparatefunctiontodotheactualprintingofthislineThissimplifiesmycodeandmakesiteasierformetounderstanditIfIwanttolearnwhatthisfunctiondoesIcanjumptoitandstudyOnceIknowwhatprint_linedoesIcanattachmymemorytothenameprint_line

andforgetaboutthedetails10IhavewrittenatinyyetpowerfulpieceofmagichereIamcallingmainagaininsidemainActuallyitrsquosnotmagicsincenothingreallyismagicalinprogrammingAlltheinformationyouneedisthereThislookslikeIamcallingthefunctioninsideitselfwhichseemslikeitshouldbeillegaltodoAskyourselfwhyshouldthatbeillegalTherersquosnotechnicalreasonwhyIcanrsquotcallanyfunctionIwantrightthereeventhismainfunctionIfafunctionissimplyajumptothetopwhereIrsquovenameditmainthencallingthisfunctionattheendofitselfwouldjumpbacktothetopandrunitagainThatwouldmakeitloopNowlookbackatline8andyoursquollseetheif-statementkeepsthisfunctionfromloopingforeverCarefullystudythisbecauseitisasignificantconceptbutdonrsquotworryifyoucanrsquotgraspitrightaway

13Istartthedefinitionfortheprint_linefunctionwhichdoestheactualencodingofeachlinefromthelanguagestxtfile

14Thisisasimplestrippingofthetrailingnonthelinestring15IfinallytakethelanguageIrsquovereceivedfromthelanguagestxtfileandencodeitintotherawbytesRemembertheDBESmnemonicDecodebytesencodestringsThenext_langvariableisastringsotogettherawbytesImustcallencode()onittoencodestringsIpasstoencode()theencodingIwantandhowtohandleerrors

16Idotheextrastepofshowingtheinverseofline15bycreatingacooked_stringvariablefromtheraw_bytesRememberDBESsaysIdecodebytesandraw_bytesisbytessoIcalldecode()onittogetaPythonstringThisstringshouldbethesameasthenext_langvariable

18Isimplyprintthembothouttoshowyouwhattheylooklike21IrsquomdonedefiningfunctionssonowIwanttoopenthelanguagestxtfile

23Theendofthescriptsimplyrunsthemainfunctionwithallthecorrectparameterstogeteverythinggoingandkick-starttheloopRememberthatthisthenjumpstowherethemainfunctionisdefinedonline5andonline10mainiscalledagaincausingthistokeeploopingTheiflineonline8willpreventourloopfromgoingforever

EncodingsDeepDive

WecannowuseourlittlescripttoexploreotherencodingsThefollowingshowsmeplayingwithdifferentencodingsandseeinghowtobreakthemFirstIrsquomdoingasimpleUTF-16encodingsoyoucanseehowitchangescomparedtoUTF-8YoucanalsouseUTF-32toseehowthatrsquosevenbiggerandgetanideaofthespacesavedwithUTF-8AfterthatItryBig5andyoursquollseethatPythondoesnotlikethatatallItthrowsupanerrorthatBig5canrsquotencodesomeofthecharactersatposition0(whichissuperhelpful)OnesolutionistotellPythontoldquoreplacerdquoanybadcharactersfortheBig5encodingThatrsquosthenextexampleandyoursquollseeitputsacharacterwhereveritfindsacharacterthatdoesnrsquotmatchtheBig5encodingsystem

BreakingItRoughideasincludethefollowing

1Findstringsoftextencodedinotherencodingsandplacethemintheex23pyfiletoseehowitbreaks

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist3ExtrachallengingRewritethisusingthebbytesinsteadoftheUTF-8stringseffectivelyreversingthescript

4IfyoucandothatthenyoucanalsobreakthesebytesbyremovingsometoseewhathappensHowmuchdoyouneedtoremovetocausePythontobreakHowmuchcanyouremovetodamagethestringoutputbutpassPythonrsquosdecodingsystem

5Usewhatyoulearnedfromitem4toseeifyoucanmanglethefilesWhaterrorsdoyougetHowmuchdamagecanyoucauseandgetthefilepastPythonrsquosdecodingsystem

Exercise24MorePractice

YouaregettingtotheendofthissectionYoushouldhaveenoughPythonldquounderyourfingersrdquotomoveontolearningabouthowprogrammingreallyworksbutyoushoulddosomemorepracticeThisexerciseislongerandallaboutbuildingupstaminaThenextexercisewillbesimilarDothemgetthemexactlyrightanddoyourchecksClickheretoviewcodeimage

ex24py

1print(Letspracticeeverything)

2print(Youdneedtoknowboutescapeswiththatdo)

3print(nnewlinesandttabs)

4

5poem=

6tThelovelyworld

7withlogicsofirmlyplanted

8cannotdiscernntheneedsoflove

9norcomprehendpassionfromintuition

10andrequiresanexplanation

11nttwherethereisnone

12

13

14print(--------------)

15print(poem)

16print(--------------)

17

18

19five=10-2+3-6

20print(fThisshouldbefivefive)

21

22defsecret_formula(started)

23jelly_beans=started500

24jars=jelly_beans1000

25crates=jars100

26returnjelly_beansjarscrates

27

28

29start_point=10000

30beansjarscrates=secret_formula(start_point)

31

32rememberthatthisisanotherwaytoformatastring

33print(Withastartingpointofformat(start_point))

34itsjustlikewithanfstring

35print(fWedhavebeansbeansjarsjarsandcrates

crates)

36

37start_point=start_point10

38

39print(Wecanalsodothatthisway)

40formula=secret_formula(start_point)

41thisisaneasywaytoapplyalisttoaformatstring

42print(Wedhavebeansjarsand

cratesformat(formula))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise24Session

$python36ex24py

Letspracticeeverything

Youdneedtoknowboutescapeswiththatdo

newlinesandtabs

--------------

Thelovelyworld

withlogicsofirmlyplanted

cannotdiscern

theneedsoflove

norcomprehendpassionfromintuition

andrequiresanexplanation

wherethereisnone

--------------

Thisshouldbefive5

Withastartingpointof10000

Wedhave5000000beans50000jarsand500crates

Wecanalsodothatthisway

Wedhave5000000beans5000jarsand50crates

StudyDrills1Makesuretodoyourchecksreaditbackwardreaditoutloudandputcommentsaboveconfusingparts

2BreakthefileonpurposethenrunittoseewhatkindsoferrorsyougetMakesureyoucanfixit

CommonStudentQuestionsWhydoyoucallthevariablejelly_beansbutthenamebeanslaterThatrsquospartofhowafunctionworksRememberthatinsidethefunctionthevariableistemporaryWhenyoureturnitthenitcanbeassignedtoavariableforlaterIrsquomjustmakinganewvariablenamedbeanstoholdthereturnvalue

WhatdoyoumeanbyreadingthecodebackwardStartatthelastlineComparethatlineinyourfiletothesamelineinmineOnceitrsquosexactlythesamemoveuptothenextlineDothisuntilyougettothefirstlineofthefile

WhowrotethatpoemIdidNotallofmypoemssuck

Exercise25EvenMorePractice

WersquoregoingtodosomemorepracticeinvolvingfunctionsandvariablestomakesureyouknowthemwellThisexerciseshouldbestraightforwardforyoutotypeinbreakdownandunderstandHoweverthisexerciseisalittledifferentYouwonrsquotberunningitInsteadyouwillimportitintoPythonandrunthefunctionsyourselfClickheretoviewcodeimage

ex25py

1defbreak_words(stuff)

2Thisfunctionwillbreakupwordsforus

3words=stuffsplit()

4returnwords

5

6defsort_words(words)

7Sortsthewords

8returnsorted(words)

9

10defprint_first_word(words)

11Printsthefirstwordafterpoppingitoff

12word=wordspop(0)

13print(word)

14

15defprint_last_word(words)

16Printsthelastwordafterpoppingitoff

17word=wordspop(-1)

18print(word)

19

20defsort_sentence(sentence)

21Takesinafullsentenceandreturnsthesorted

words

22words=break_words(sentence)

23returnsort_words(words)

24

25defprint_first_and_last(sentence)

26Printsthefirstandlastwordsofthesentence

27words=break_words(sentence)

28print_first_word(words)

29print_last_word(words)

30

31defprint_first_and_last_sorted(sentence)

32Sortsthewordsthenprintsthefirstandlastone

33words=sort_sentence(sentence)

34print_first_word(words)

35print_last_word(words)Firstrunthiswithpython36

ex25pytofindanyerrorsyouhavemadeOnceyouhavefoundallof

theerrorsyoucanandfixedthemyouwillthenwanttofollowthe

WhatYouShouldSeesectiontocompletetheexercise

WhatYouShouldSeeInthisexercisewersquoregoingtointeractwithyourex25pyfileinsidethepython36interpreteryouusedperiodicallytodocalculationsYourunpython36fromtheTerminallikethisClickheretoviewcodeimage

$python36

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtYouroutputshouldlooklikemineandafterthegtcharacter

(calledtheprompt)youcantypePythoncodeinanditwillrun

immediatelyUsingthisIwantyoutotypeeachoftheselinesof

Pythoncodeintopython36andseewhatitdoesClickheretoview

codeimage

Exercise25PythonSession

1importex25

2sentence=Allgoodthingscometothosewhowait

3words=ex25break_words(sentence)

4words

5sorted_words=ex25sort_words(words)

6sorted_words

7ex25print_first_word(words)

8ex25print_last_word(words)

9words

10ex25print_first_word(sorted_words)

11ex25print_last_word(sorted_words)

12sorted_words

13sorted_words=ex25sort_sentence(sentence)

14sorted_words

15ex25print_first_and_last(sentence)

16ex25print_first_and_last_sorted(sentence)Herersquoswhatitlooks

likewhenIworkwiththeex25pymoduleinpython36Clickhereto

viewcodeimage

Exercise25PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtimportex25

gtgtgtsentence=Allgoodthingscometothosewhowait

gtgtgtwords=ex25break_words(sentence)

gtgtgtwords

[Allgoodthingscometothosewhowait]

gtgtgtsorted_words=ex25sort_words(words)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_word(words)

All

gtgtgtex25print_last_word(words)

wait

gtgtgtwords

[goodthingscometothosewho]

gtgtgtex25print_first_word(sorted_words)

All

gtgtgtex25print_last_word(sorted_words)

who

gtgtgtsorted_words

[comegoodthingsthosetowait]

gtgtgtsorted_words=ex25sort_sentence(sentence)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_and_last(sentence)

All

wait

gtgtgtex25print_first_and_last_sorted(sentence)

All

whoAsyougothrougheachoftheselinesmakesureyoucanfindthe

functionthatrsquosbeingruninex25pyandunderstandhoweachone

worksIfyougetdifferentresultsorerroryoursquollhavetogofix

yourcodeexitpython36andstartover

StudyDrills1TaketheremaininglinesoftheWhatYouShouldSeeoutputandfigureoutwhattheyaredoingMakesureyouunderstandhowyouarerunningyourfunctionsintheex25module

2Trydoingthishelp(ex25)andalsohelp(ex25break_words)Noticehowyougethelpforyourmoduleandhowthehelpisthoseoddstringsyouputaftereachfunctioninex25Thosespecialstringsarecalleddocumentationcommentsandwersquollbeseeingmoreofthem

3Typingex25isannoyingAshortcutistodoyourimportlikethisfromex25importThisislikesayingldquoImporteverythingfromex25rdquoProgrammerslikesayingthingsbackwardStartanewsessionandseehowallyourfunctionsarerightthere

4TrybreakingyourfileandseewhatitlookslikeinpythonwhenyouuseitYouwillhavetoquitpythonwithquit()tobeabletoreloadit

CommonStudentQuestionsIgetNoneprintedoutforsomeofthefunctionsYouprobablyhaveafunctionthatismissingthereturnattheendGobackwardthroughthefileandconfirmthateverylineisright

Iget-bashimportcommandnotfoundwhenItypeimportex25PayattentiontowhatIrsquomdoingintheWhatYouShouldSeesectionIrsquomdoingthisinPythonnotintheTerminalThatmeansyoufirstrunPython

IgetImportErrorNomodulenamedex25pywhenItypeimportex25pyDonrsquotaddthepytotheendPythonknowsthefileendsinpysoyoujusttypeimportex25

IgetSyntaxErrorinvalidsyntaxwhenIrunthisThatmeansyouhavesomethinglikeamissing(ororsimilarsyntaxerroronthatlineoraboveitAnytimeyougetthaterrorstartatthelineitmentionsandcheckthatitrsquosrightthengobackwardcheckingeachlineabovethat

HowcanthewordspopfunctionchangethewordsvariableThatrsquosacomplicatedquestionbutinthiscasewordsisalistandbecauseofthatyoucangiveitcommandsanditrsquollretaintheresultsofthosecommandsThisissimilartohowfilesandmanyotherthingsworkedwhenyouwereworkingwiththem

WhenshouldIprintinsteadofreturninafunctionThereturnfromafunctiongivesthelineofcodethatcalledthefunctionaresultYoucanthinkofafunctionastakinginputthroughitsargumentsandreturningoutputthroughreturnTheprintiscompletelyunrelatedtothisandonlydealswithprintingoutputtotheTerminal

Exercise26CongratulationsTakeaTest

YouarealmostdonewiththefirsthalfofthebookThesecondhalfiswherethingsgetinterestingYouwilllearnlogicandbeabletodousefulthingslikemakedecisionsBeforeyoucontinueIhaveaquizforyouThisquizwillbeveryhardbecauseitrequiresyoutofixsomeoneelsersquoscodeWhenyouareaprogrammeryouoftenhavetodealwithotherprogrammersrsquocodemdashandalsowiththeirarroganceProgrammerswillveryfrequentlyclaimthattheircodeisperfectTheseprogrammersarestupidpeoplewhocarelittleforothersAgoodprogrammerassumeslikeagoodscientistthattherersquosalwayssomeprobabilitytheircodeiswrongGoodprogrammersstartfromthepremisethattheirsoftwareisbrokenandthenworktoruleoutallpossiblewaysitcouldbewrongbeforefinallyadmittingthatmaybeitreallyistheotherguyrsquoscodeInthisexerciseyouwillpracticedealingwithabadprogrammerbyfixingabadprogrammerrsquoscodeIhavepoorlycopiedExercises24and25intoafileandremovedrandomcharactersandaddedflawsMostoftheerrorsarethingsPythonwilltellyouwhilesomeofthemarematherrorsyoushouldfindOthersareformattingerrorsorspellingmistakesinthestringsAlloftheseerrorsareverycommonmistakesallprogrammersmakemdashevenexperiencedonesYourjobinthisexerciseistocorrectthisfileUseallofyourskillstomakethisfilebetterAnalyzeitfirstmaybeprintingitouttoedititlikeyouwouldaschooltermpaperFixeachflawandkeeprunningitandfixingituntilthescriptrunsperfectlyTrynottogethelpIfyougetstucktakeabreakandcomebacktoitlaterEvenifthistakesdaystodobustthroughitandmakeitrightThepointofthisexerciseisnrsquottotypeitinbuttofixanexistingfileTodothatyoumustgotohttplearnpythonthehardwayorgpython3exercise26txtCopy-pastethecodeintoafilenamedex26pyThisistheonlytimeyouareallowedtocopy-paste

CommonStudentQuestionsDoIhavetoimportex25pyorcanIjustremovethereferencestoitYoucandoeitherThisfilehasthefunctionsfromex25

thoughsofirstgowithremovingreferencestoitCanIrunthecodewhileIrsquomfixingitYoumostcertainlymayThecomputeristheretohelpsouseitasmuchaspossible

Exercise27MemorizingLogic

TodayisthedayyoustartlearningaboutlogicUptothispointyouhavedoneeverythingyoupossiblycanreadingandwritingfilestotheTerminalandhavelearnedquitealotofthemathcapabilitiesofPythonFromnowonyouwillbelearninglogicYouwonrsquotlearncomplextheoriesthatacademicslovetostudybutjustthebasiclogicthatmakesrealprogramsworkandthatrealprogrammersneedeverydayLearninglogichastocomeafteryoudosomememorizationIwantyoutodothisexerciseforanentireweekDonotfalterEvenifyouareboredoutofyourmindkeepdoingitThisexercisehasasetoflogictablesyoumustmemorizetomakeiteasierforyoutodothelaterexercisesIrsquomwarningyouthiswonrsquotbefunatfirstItwillbedownrightboringandtediousbutthisteachesyouaveryimportantskillyouwillneedasaprogrammerYouwillneedtobeabletomemorizeimportantconceptsinyourlifeMostoftheseconceptswillbeexcitingonceyougetthemYouwillstrugglewiththemlikewrestlingasquidthenonedayyouwillunderstanditAllthatworkmemorizingthebasicspaysoffbiglaterHerersquosatiponhowtomemorizesomethingwithoutgoinginsaneDoatinybitatatimethroughoutthedayandmarkdownwhatyouneedtoworkonmostDonottrytositdownfortwohoursstraightandmemorizethesetablesThiswonrsquotworkYourbrainwillonlyretainwhateveryoustudiedinthefirst15or30minutesanywayInsteadcreateabunchofindexcardswitheachcolumnontheleft(TrueorFalse)onthefrontandthecolumnontherightonthebackYoushouldthentakethemoutseetheldquoTrueorFalserdquoandimmediatelysayldquoTruerdquoKeeppracticinguntilyoucandothisOnceyoucandothatstartwritingoutyourowntruthtableseachnightintoanotebookDonotjustcopythemTrytodothemfrommemoryWhenyougetstuckglancequicklyattheonesIhaveheretorefreshyourmemoryDoingthiswilltrainyourbraintorememberthewholetableDonotspendmorethanoneweekonthisbecauseyouwillbeapplyingitasyougo

TheTruthTermsInPythonwehavethefollowingterms(charactersandphrases)fordeterminingifsomethingisldquoTruerdquoorldquoFalserdquoLogiconacomputerisallaboutseeingifsomecombinationofthesecharactersandsomevariablesisTrueatthatpointin

somecombinationofthesecharactersandsomevariablesisTrueatthatpointintheprogram

bullandbullorbullnotbull=(notequal)bull==(equal)bullgt=(greater-than-equal)bulllt=(less-than-equal)bullTruebullFalse

YouactuallyhaverunintothesecharactersbeforebutmaybenotthetermsTheterms(andornot)actuallyworkthewayyouexpectthemtojustlikeinEnglish

TheTruthTablesWewillnowusethesecharacterstomakethetruthtablesyouneedtomemorize

NowusethesetablestowriteupyourowncardsandspendtheweekmemorizingthemRememberthoughthereisnofailinginthisbookjusttryingashardasyoucaneachdayandthenalittlebitmore

CommonStudentQuestionsCanrsquotIjustlearntheconceptsbehindBooleanalgebraandnotmemorizethisSureyoucandothatbutthenyoursquollhavetoconstantlygothroughtherulesforBooleanalgebrawhileyoucodeIfyoumemorizethesefirstitnotonlybuildsyourmemorizationskillsitalsomakestheseoperationsnaturalAfterthattheconceptofBooleanalgebraiseasyButdowhateverworksforyou

Exercise28BooleanPractice

ThelogiccombinationsyoulearnedfromthelastexercisearecalledBooleanlogicexpressionsBooleanlogicisusedeverywhereinprogrammingItisafundamentalpartofcomputationandknowingtheexpressionsisakintoknowingyourscalesinmusicInthisexerciseyouwilltakethelogicexercisesyoumemorizedandstarttryingthemoutinPythonTakeeachoftheselogicproblemsandwritewhatyouthinktheanswerwillbeIneachcaseitwillbeeitherTrueorFalseOnceyouhavetheanswerswrittendownstartPythoninyourTerminalandtypeeachlogicproblemintoconfirmyouranswers

1TrueandTrue2FalseandTrue31==1and2==14test==test51==1or2=16Trueand1==17Falseand0=08Trueor1==19test==testing101=0and2==111test=testing12test==113not(TrueandFalse)14not(1==1and0=1)15not(10==1or1000==1000)16not(1=10or3==4)17not(testing==testingandZed==CoolGuy)

181==1and(not(testing==1or1==0))19chunky==baconand(not(3==4or3==3))203==3and(not(testing==testingor

Python==Fun))

IwillalsogiveyouatricktohelpyoufigureoutthemorecomplicatedonestowardtheendWheneveryouseetheseBooleanlogicstatementsyoucansolvethemeasilybythissimpleprocess1Findanequalitytest(==or=)andreplaceitwithitstruth

2Findeachandorinsideparenthesesandsolvethosefirst3Findeachnotandinvertit4Findanyremainingandorandsolveit5WhenyouaredoneyoushouldhaveTrueorFalse

Iwilldemonstratewithavariationonitem20Clickheretoviewcodeimage

3=4andnot(testing=testorPython==Python)

HerersquosmegoingthrougheachofthestepsandshowingyouthetranslationuntilIrsquoveboileditdowntoasingleresult1Solveeachequalitytest

3=4isTrueTrueandnot(testing=testorPython==Python)

testing=testisTrueTrueandnot(TrueorPython==Python)

Python==PythonTrueandnot(TrueorTrue)2Findeachandorinparentheses()(TrueorTrue)isTrueTrueandnot(True)

3Findeachnotandinvertitnot(True)isFalseTrueandFalse4FindanyremainingandorsandsolvethemTrueandFalseisFalse

WiththatwersquoredoneandknowtheresultisFalse

WarningThemorecomplicatedonesmayseemveryhardatfirstYoushouldbeabletotakeagoodfirststabatsolvingthembutdonotgetdiscouragedIrsquomjustgettingyouprimedformoreoftheseldquologicgymnasticsrdquosothatlatercoolstuffismucheasierJuststickwithitandkeeptrackofwhatyougetwrongbutdonotworrythatitrsquosnotgettinginyourheadquiteyetItrsquollcome

WhatYouShouldSeeAfteryouhavetriedtoguessatthesethisiswhatyoursessionwithPythonmightlooklikeClickheretoviewcodeimage

$python36

Python251(r25154863Feb62009190212)

[GCC401(AppleIncbuild5465)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtTrueandTrue

True

gtgtgt1==1and2==2

True

StudyDrills1TherearealotofoperatorsinPythonsimilarto=and==TrytofindasmanyldquoequalityoperatorsrdquoasyoucanTheyshouldbelikeltorlt=

2WriteoutthenamesofeachoftheseequalityoperatorsForexampleIcall=ldquonotequalrdquo

3PlaywithPythonbytypingoutnewBooleanoperatorsandbeforeyoupressEntertrytoshoutoutwhatitisDonotthinkaboutitShoutthefirstthingthatcomestomindWriteitdownthenpressEnterandkeeptrackofhowmanyyougetrightandwrong

4Throwawaythepieceofpaperfrom3soyoudonotaccidentallytrytouseitlater

CommonStudentQuestionsWhydoestestandtestreturntestor1and1return1insteadofTruePythonandmanylanguagesliketoreturnoneoftheoperandstotheirBooleanexpressionsratherthanjustTrueorFalseThismeansthatifyoudidFalseand1yougetthefirstoperand(False)butifyoudoTrueand1yougetthesecond(1)Playwiththisabit

Isthereanydifferencebetween=andltgtPythonhasdeprecatedltgtinfavorof=souse=Otherthanthatthereshouldbenodifference

IsnrsquotthereashortcutYesAnyandexpressionthathasaFalseisimmediatelyFalsesoyoucanstopthereAnyorexpressionthathasaTrueisimmediatelyTruesoyoucanstopthereButmakesurethatyoucanprocessthewholeexpressionbecauselateritbecomeshelpful

Exercise29WhatIf

HereisthenextscriptofPythonyouwillenterwhichintroducesyoutotheif-statementTypethisinmakeitrunexactlyrightandthenwersquollseeifyourpracticehaspaidoffClickheretoviewcodeimage

ex29py

1people=20

2cats=30

3dogs=15

4

5

6ifpeopleltcats

7print(ToomanycatsTheworldisdoomed)

8

9ifpeoplegtcats

10print(NotmanycatsTheworldissaved)

11

12ifpeopleltdogs

13print(Theworldisdrooledon)

14

15ifpeoplegtdogs

16print(Theworldisdry)

17

18

19dogs+=5

20

21ifpeoplegt=dogs

22print(Peoplearegreaterthanorequaltodogs)

23

24ifpeoplelt=dogs

25print(Peoplearelessthanorequaltodogs)

26

27

28ifpeople==dogs

29print(Peoplearedogs)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise29Session

$python36ex29py

ToomanycatsTheworldisdoomed

Theworldisdry

Peoplearegreaterthanorequaltodogs

Peoplearelessthanorequaltodogs

Peoplearedogs

StudyDrillsInthisStudyDrilltrytoguesswhatyouthinktheif-statementisandwhatitdoesTrytoanswerthesequestionsinyourownwordsbeforemovingontothenextexercise

1Whatdoyouthinktheifdoestothecodeunderit2Whydoesthecodeundertheifneedtobeindentedfourspaces3Whathappensifitisnrsquotindented4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryit

5Whathappensifyouchangetheinitialvaluesforpeoplecatsanddogs

CommonStudentQuestionsWhatdoes+=meanThecodex+=1isthesameasdoingx=x+1butinvolveslesstypingYoucancallthistheldquoincrementbyrdquooperatorThesamegoesfor-=andmanyotherexpressionsyoursquolllearnlater

Exercise30ElseandIf

Inthelastexerciseyouworkedoutsomeif-statementsandthentriedtoguesswhattheyareandhowtheyworkBeforeyoulearnmoreIrsquollexplainwhateverythingisbyansweringthequestionsyouhadfromthepreviousStudyDrillssectionYoudidtheStudyDrillsright

1WhatdoyouthinktheifdoestothecodeunderitAnif-statementcreateswhatiscalledaldquobranchrdquointhecodeItrsquoskindoflikethosechooseyourownadventurebookswhereyouareaskedtoturntoonepageifyoumakeonechoiceandanotherifyougoadifferentdirectionTheif-statementtellsyourscriptldquoIfthisBooleanexpressionisTruethenrunthecodeunderitotherwiseskipitrdquo

2WhydoesthecodeundertheifneedtobeindentedfourspacesAcolonattheendofalineishowyoutellPythonyouaregoingtocreateanewldquoblockrdquoofcodeandthenindentingfourspacestellsPythonwhatlinesofcodeareinthatblockThisisexactlythesamethingyoudidwhenyoumadefunctionsinthefirsthalfofthebook

3WhathappensifitisnrsquotindentedIfitisnrsquotindentedyouwillmostlikelycreateaPythonerrorPythonexpectsyoutoindentsomethingafteryouendalinewitha(colon)

4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryitYesyoucanandtheycanbeascomplexasyoulikealthoughreallycomplexthingsgenerallyarebadstyle

5WhathappensifyouchangetheinitialvaluesforpeoplecatsanddogsBecauseyouarecomparingnumbersifyouchangethenumbersdifferentif-statementswillevaluatetoTrueandtheblocksofcodeunderthemwillrunGobackandputdifferentnumbersinandseeifyoucanfigureoutinyourheadwhichblocksofcodewillrun

ComparemyanswerstoyouranswersandmakesureyoureallyunderstandtheconceptofaldquoblockrdquoofcodeThisisimportantforwhenyoudothenextexercisewhereyouwriteallthepartsofif-statementsthatyoucanuseTypethisoneinandmakeitworktooClickheretoviewcodeimage

ex30py

1people=30

2cars=40

3trucks=15

4

5

6ifcarsgtpeople

7print(Weshouldtakethecars)

8elifcarsltpeople

9print(Weshouldnottakethecars)

10else

11print(Wecantdecide)

12

13iftrucksgtcars

14print(Thatstoomanytrucks)

15eliftrucksltcars

16print(Maybewecouldtakethetrucks)

17else

18print(Westillcantdecide)

19

20ifpeoplegttrucks

21print(Alrightletsjusttakethetrucks)

22else

23print(Fineletsstayhomethen)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise30Session

$python36ex30py

Weshouldtakethecars

Maybewecouldtakethetrucks

Alrightletsjusttakethetrucks

StudyDrills1Trytoguesswhatelifandelsearedoing2Changethenumbersofcarspeopleandtrucksandthentracethrougheachif-statementtoseewhatwillbeprinted

3TrysomemorecomplexBooleanexpressionslikecarsgtpeopleortrucksltcars

4Aboveeachlinewriteacommentdescribingwhatthelinedoes

CommonStudentQuestions

CommonStudentQuestionsWhathappensifmultipleelifblocksareTruePythonstartsatthetopandrunsthefirstblockthatisTruesoitwillrunonlythefirstone

Exercise31MakingDecisions

InthefirsthalfofthisbookyoumostlyjustprintedoutstringsandcalledfunctionsbuteverythingwasbasicallyinastraightlineYourscriptsranstartingatthetopandwenttothebottomwheretheyendedIfyoumadeafunctionyoucouldrunthatfunctionlaterbutitstilldidnrsquothavethekindofbranchingyouneedtoreallymakedecisionsNowthatyouhaveifelseandelifyoucanstarttomakescriptsthatdecidethingsInthelastscriptyouwroteoutasimplesetoftestsaskingsomequestionsInthisscriptyouwillasktheuserquestionsandmakedecisionsbasedontheiranswersWritethisscriptandthenplaywithitquitealottofigureitoutClickheretoviewcodeimage

ex31py

1print(Youenteradarkroomwithtwodoors

2Doyougothroughdoor1ordoor2)

3

4door=input(gt)

5

6ifdoor==1

7print(Theresagiantbearhereeatingacheesecake)

8print(Whatdoyoudo)

9print(1Takethecake)

10print(2Screamatthebear)

11

12bear=input(gt)

13

14ifbear==1

15print(ThebeareatsyourfaceoffGoodjob)

16elifbear==2

17print(ThebeareatsyourlegsoffGoodjob)

18else

19print(fWelldoingbearisprobablybetter)

20print(Bearrunsaway)

21

22elifdoor==2

23print(YoustareintotheendlessabyssatCthulhus

retina)

24print(1Blueberries)

25print(2Yellowjacketclothespins)

26print(3Understandingrevolversyellingmelodies)

27

28insanity=input(gt)

29

30ifinsanity==1orinsanity==2

31print(Yourbodysurvivespoweredbyamindofjello)

32print(Goodjob)

33else

34print(Theinsanityrotsyoureyesintoapoolof

muck)

35print(Goodjob)

36

37else

38print(YoustumblearoundandfallonaknifeanddieGood

job)Akeypointhereisthatyouarenowputtingtheif-statements

insideif-statementsascodethatcanrunThisisverypowerfuland

canbeusedtocreateldquonestedrdquodecisionswhereonebranchleadsto

anotherandanother

Makesureyouunderstandthisconceptofif-statementsinsideif-statementsInfactdotheStudyDrillstoreallynailit

WhatYouShouldSeeHereismeplayingthislittleadventuregameIdonotdosowellClickheretoviewcodeimage

Exercise31Session

$python36ex31py

Youenteradarkroomwithtwodoors

Doyougothroughdoor1ordoor2

gt1

Theresagiantbearhereeatingacheesecake

Whatdoyoudo

1Takethecake

2Screamatthebear

gt2

ThebeareatsyourlegsoffGoodjob

StudyDrills1MakenewpartsofthegameandchangewhatdecisionspeoplecanmakeExpandthegameoutasmuchasyoucanbeforeitgetsridiculous

2WriteacompletelynewgameMaybeyoudonrsquotlikethisonesomakeyourownThisisyourcomputerdowhatyouwant

CommonStudentQuestions

CommonStudentQuestionsCanyoureplaceelifwithasequenceofif-elsecombinationsYoucaninsomesituationsbutitdependsonhoweachifelseiswrittenItalsomeansthatPythonwillcheckeveryif-elsecombinationratherthanjustthefirstfalseoneslikeitwouldwithif-elif-elseTrytomakesomeofthesetofigureoutthedifferences

HowdoItellwhetheranumberisbetweenarangeofnumbersYouhavetwooptionsUse0ltxlt10or1lt=xlt10whichisclassicnotationorusexinrange(110)

WhatifIwantedmoreoptionsintheif-elif-elseblocksAddmoreelifblocksforeachpossiblechoice

Exercise32LoopsandLists

YoushouldnowbeabletodosomeprogramsthataremuchmoreinterestingIfyouhavebeenkeepingupyoushouldrealizethatnowyoucancombinealltheotherthingsyouhavelearnedwithif-statementsandBooleanexpressionstomakeyourprogramsdosmartthingsHoweverprogramsalsoneedtodorepetitivethingsveryquicklyWearegoingtouseafor-loopinthisexercisetobuildandprintvariouslistsWhenyoudotheexerciseyouwillstarttofigureoutwhattheyareIwonrsquottellyourightnowYouhavetofigureitoutBeforeyoucanuseafor-loopyouneedawaytostoretheresultsofloopssomewhereThebestwaytodothisiswithlistsAlistisexactlywhatthenamesaysacontainerofthingsthatareorganizedinorderfromfirsttolastItrsquosnotcomplicatedyoujusthavetolearnanewsyntaxFirstherersquoshowyoumakelistsClickheretoviewcodeimage

hairs=[brownblondred]

eyes=[brownbluegreen]

weights=[1234]

Youstartthelistwiththe[(leftbracket)whichldquoopensrdquothelistThenyouputeachitemyouwantinthelistseparatedbycommassimilartofunctionargumentsLastlyendthelistwitha](rightbracket)toindicatethatitrsquosoverPythonthentakesthislistandallitscontentsandassignsthemtothevariable

WarningThisiswherethingsgettrickyforpeoplewhocanrsquotcodeYourbrainhasbeentaughtthattheworldisflatRememberinthelastexercisewhereyouputif-statementsinsideif-statementsThatprobablymadeyourbrainhurtbecausemostpeopledonotponderhowtoldquonestrdquothingsinsidethingsInprogrammingnestedstructuresareallovertheplaceYouwillfindfunctionsthatcallotherfunctionsthathaveif-statementsthathavelistswithlistsinsidelistsIfyouseeastructurelikethisthatyoucanrsquotfigureouttakeoutapencilandpaperandbreakitdownmanuallybitbybituntilyouunderstandit

Wenowwillbuildsomelistsusingsomefor-loopsandprintthemoutClickheretoviewcodeimage

ex32py

1the_count=[12345]

2fruits=[applesorangespearsapricots]

3change=[1pennies2dimes3quarters]

4

5thisfirstkindoffor-loopgoesthroughalist

6fornumberinthe_count

7print(fThisiscountnumber)

8

9sameasabove

10forfruitinfruits

11print(fAfruitoftypefruit)

12

13alsowecangothroughmixedliststoo

14noticewehavetousesincewedontknowwhatsinit

15foriinchange

16print(fIgoti)

17

18wecanalsobuildlistsfirststartwithanemptyone

19elements=[]

20

21thenusetherangefunctiontodo0to5counts

22foriinrange(06)

23print(fAddingitothelist)

24appendisafunctionthatlistsunderstand

25elementsappend(i)

26

27nowwecanprintthemouttoo

28foriinelements

29print(fElementwasi)

WhatYouShouldSee

Exercise32Session

$python36ex32py

Thisiscount1

Thisiscount2

Thisiscount3

Thisiscount4

Thisiscount5

Afruitoftypeapples

Afruitoftypeoranges

Afruitoftypepears

Afruitoftypeapricots

Igot1

Igotpennies

Igot2

Igotdimes

Igot3

Igotquarters

Adding0tothelist

Adding1tothelist

Adding2tothelist

Adding3tothelist

Adding4tothelist

Adding5tothelist

Elementwas0

Elementwas1

Elementwas2

Elementwas3

Elementwas4

Elementwas5

StudyDrills1TakealookathowyouusedrangeLookuptherangefunctiontounderstandit

2Couldyouhaveavoidedthatfor-loopentirelyonline22andjustassignedrange(06)directlytoelements

3FindthePythondocumentationonlistsandreadaboutthemWhatotheroperationscanyoudotolistsbesidesappend

CommonStudentQuestionsHowdoyoumakea2-dimensional(2D)listThatrsquosalistinalistlikethis[[123][456]]

ArenrsquotlistsandarraysthesamethingThatdependsonthelanguageandtheimplementationInclassictermsalistisverydifferentfromanarraybecauseofhowtheyrsquoreimplementedInRubythoughtheycallthesearraysInPythontheycallthemlistsJustcalltheselistsfornowsincethatrsquoswhatPythoncallsthem

Whyisafor-loopabletouseavariablethatisnrsquotdefinedyetThevariableisdefinedbythefor-loopwhenitstartsinitializingittothecurrentelementoftheloopiterationeachtimethrough

Whydoesforiinrange(13)onlylooptwotimesinsteadofthreetimesTherange()functiononlydoesnumbersfromthefirsttothelastnotincludingthelastSoitstopsattwonotthreeintheprecedingThisturnsouttobethemostcommonwaytodothiskindofloop

Whatdoeselementsappend()doItsimplyappendstotheendofthelistOpenupthePythonshellandtryafewexampleswithalistyoumakeAnytimeyourunintothingslikethisalwaystrytoplaywiththeminteractivelyinthePythonshell

Exercise33WhileLoops

Nowtototallyblowyourmindwithanewloopthewhile-loopAwhile-loopwillkeepexecutingthecodeblockunderitaslongasaBooleanexpressionisTrueWaityouhavebeenkeepingupwiththeterminologyrightThatifwewritealineandenditwitha(colon)thenthattellsPythontostartanewblockofcodeThenweindentandthatrsquosthenewcodeThisisallaboutstructuringyourprogramssothatPythonknowswhatyoumeanIfyoudonotgetthatideathengobackanddosomemoreworkwithif-statementsfunctionsandthefor-loopuntilyougetitLateronwersquollhavesomeexercisesthatwilltrainyourbraintoreadthesestructuressimilartohowweburnedBooleanexpressionsintoyourbrainBacktowhile-loopsWhattheydoissimplydoatestlikeanif-statementbutinsteadofrunningthecodeblockoncetheyjumpbacktotheldquotoprdquowherethewhileisandrepeatAwhile-looprunsuntiltheexpressionisFalseHerersquostheproblemwithwhile-loopsSometimestheydonotstopThisisgreatifyourintentionistojustkeeploopinguntiltheendoftheuniverseOtherwiseyoualmostalwayswantyourloopstoendeventuallyToavoidtheseproblemstherearesomerulestofollow1Makesurethatyouusewhile-loopssparinglyUsuallyafor-loopisbetter

2ReviewyourwhilestatementsandmakesurethattheBooleantestwillbecomeFalseatsomepoint

3Whenindoubtprintoutyourtestvariableatthetopandbottomofthewhile-looptoseewhatitrsquosdoing

Inthisexerciseyoulearnthewhile-loopwhiledoingthesethreechecksClickheretoviewcodeimage

ex33py

1i=0

2numbers=[]

3

4whileilt6

5print(fAtthetopiisi)

6numbersappend(i)

7

8i=i+1

9print(Numbersnownumbers)

10print(fAtthebottomiisi)

11

12

13print(Thenumbers)

14

15fornuminnumbers

16print(num)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise33Session

$python36ex33py

Atthetopiis0

Numbersnow[0]

Atthebottomiis1

Atthetopiis1

Numbersnow[01]

Atthebottomiis2

Atthetopiis2

Numbersnow[012]

Atthebottomiis3

Atthetopiis3

Numbersnow[0123]

Atthebottomiis4

Atthetopiis4

Numbersnow[01234]

Atthebottomiis5

Atthetopiis5

Numbersnow[012345]

Atthebottomiis6

Thenumbers

0

1

2

3

4

5

StudyDrills

1Convertthiswhile-looptoafunctionthatyoucancallandreplace6inthetest(ilt6)withavariable

2Usethisfunctiontorewritethescripttotrydifferentnumbers3Addanothervariabletothefunctionargumentsthatyoucanpassinthatletsyouchangethe+1online8soyoucanchangehowmuchitincrementsby

4Rewritethescriptagaintousethisfunctiontoseewhateffectthathas5Writeittousefor-loopsandrangeDoyouneedtheincrementorinthemiddleanymoreWhathappensifyoudonotgetridofit

Ifatanytimeyouaredoingthisitgoescrazy(itprobablywill)justholddownCTRLandpressc(CTRL-c)andtheprogramwillabort

CommonStudentQuestionsWhatrsquosthedifferencebetweenafor-loopandawhile-loopAfor-loopcanonlyiterate(loop)ldquooverrdquocollectionsofthingsAwhile-loopcandoanykindofiteration(looping)youwantHoweverwhile-loopsarehardertogetrightandyounormallycangetmanythingsdonewithfor-loops

LoopsarehardHowdoIfigurethemoutThemainreasonpeopledonrsquotunderstandloopsisbecausetheycanrsquotfollowtheldquojumpingrdquothatthecodedoesWhenalooprunsitgoesthroughitsblockofcodeandattheenditjumpsbacktothetopTovisualizethisputprintstatementsallovertheloopprintingoutwhereintheloopPythonisrunningandwhatthevariablesaresettoatthosepointsWriteprintlinesbeforetheloopatthetopoftheloopinthemiddleandatthebottomStudytheoutputandtrytounderstandthejumpingthatrsquosgoingon

Exercise34AccessingElementsofLists

ListsareprettyusefulbutunlessyoucangetatthethingsinthemtheyarenrsquotallthatgoodYoucanalreadygothroughtheelementsofalistinorderbutwhatifyouwantsaythefifthelementYouneedtoknowhowtoaccesstheelementsofalistHerersquoshowyouwouldaccessthefirstelementofalistClickheretoviewcodeimage

animals=[beartigerpenguinzebra]

bear=animals[0]

Youtakealistofanimalsandthenyougetthefirst(1st)oneusing0HowdoesthatworkBecauseofthewaymathworksPythonstartsitslistsat0ratherthan1ItseemsweirdbuttherearemanyadvantagestothiseventhoughitismostlyarbitraryThebestwaytoexplainwhyisbyshowingyouthedifferencebetweenhowyouusenumbersandhowprogrammersusenumbersImagineyouarewatchingthefouranimalsinourlist([beartigerpenguinzebra])runinaraceTheycrossthefinishlineintheorderwehavetheminthislistTheracewasreallyexcitingbecausetheanimalsdidnrsquoteateachotherandsomehowmanagedtorunaraceYourfriendshowsuplateandwantstoknowwhowonDoesyourfriendsayldquoHeywhocameinzerothrdquoNohesaysldquoHeywhocameinfirstrdquoThisisbecausetheorderoftheanimalsisimportantYoucanrsquothavethesecondanimalwithoutthefirst(1st)animalandyoucanrsquothavethethirdwithoutthesecondItrsquosalsoimpossibletohavealdquozerothrdquoanimalsincezeromeansnothingHowcanyouhaveanothingwinaraceItjustdoesnrsquotmakesenseWecallthesekindsofnumbersldquoordinalrdquonumbersbecausetheyindicateanorderingofthingsProgrammershowevercanrsquotthinkthiswaybecausetheycanpickanyelementoutofalistatanypointToprogrammersthelistofanimalsismorelikeadeckofcardsIftheywantthetigertheygrabitIftheywantthezebratheycantakeittooThisneedtopullelementsoutoflistsatrandommeansthattheyneedawaytoindicateelementsconsistentlybyanaddressoranldquoindexrdquoandthebestwaytodothatistostarttheindicesat0TrustmeonthisthemathiswayeasierforthesekindsofaccessesThiskindofnumberisaldquocardinalrdquonumberandmeansyoucanpickatrandomsothereneedstobea0elementHowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourself

HowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourselfldquoIwantthethirdanimalrdquoyoutranslatethisldquoordinalrdquonumbertoaldquocardinalrdquonumberbysubtracting1Theldquothirdrdquoanimalisatindex2andisthepenguinYouhavetodothisbecauseyouhavespentyourwholelifeusingordinalnumbersandnowyouhavetothinkincardinalJustsubtract1andyoursquoregoodRememberordinal==ordered1stcardinal==cardsatrandom0LetrsquospracticethisTakethislistofanimalsandfollowtheexerciseswhereItellyoutowritedownwhatanimalyougetforthatordinalorcardinalnumberRememberifIsayldquofirstrdquoldquosecondrdquothenIrsquomusingordinalsosubtract1IfIgiveyoucardinal(likeldquoTheanimalat1rdquo)thenuseitdirectlyClickheretoviewcodeimage

animals=[bearpython36peacockkangaroowhale

platypus]

1Theanimalat12Thethird(3rd)animal3Thefirst(1st)animal4Theanimalat35Thefifth(5th)animal6Theanimalat27Thesixth(6th)animal8Theanimalat4

ForeachofthesewriteoutafullsentenceoftheformldquoThefirst(1st)animalisat0andisabearrdquoThensayitbackwardsldquoTheanimalat0isthe1stanimalandisabearrdquoUseyourPythontocheckyouranswers

StudyDrills1Withwhatyouknowofthedifferencebetweenthesetypesofnumberscanyouexplainwhytheyear2010inldquoJanuary12010rdquoreallyis2010andnot2009(Hintyoucanrsquotpickyearsatrandom)

2Writesomemorelistsandworkoutsimilarindexesuntilyoucantranslatethem

3UsePythontocheckyouranswers

Warning

ProgrammerswilltellyoutoreadthisguynamedDijkstraonthissubjectIrecommendyouavoidhiswritingsonthisunlessyouenjoybeingyelledatbysomeonewhostoppedprogrammingatthesametimeprogrammingstarted

Exercise35BranchesandFunctions

Youhavelearnedif-statementsfunctionsandlistsNowitrsquostimetobendyourmindTypethisinandseeifyoucanfigureoutwhatitrsquosdoingClickheretoviewcodeimage

ex35py

1fromsysimportexit

2

3defgold_room()

4print(ThisroomisfullofgoldHowmuchdoyoutake)

5

6choice=input(gt)

7if0inchoiceor1inchoice

8how_much=int(choice)

9else

10dead(Manlearntotypeanumber)

11

12ifhow_muchlt50

13print(Niceyourenotgreedyyouwin)

14exit(0)

15else

16dead(Yougreedybastard)

17

18

19defbear_room()

20print(Thereisabearhere)

21print(Thebearhasabunchofhoney)

22print(Thefatbearisinfrontofanotherdoor)

23print(Howareyougoingtomovethebear)

24bear_moved=False

25

26whileTrue

27choice=input(gt)

28

29ifchoice==takehoney

30dead(Thebearlooksatyouthenslapsyourface

off)

31elifchoice==tauntbearandnotbear_moved

32print(Thebearhasmovedfromthedoor)

33print(Youcangothroughitnow)

34bear_moved=True

35elifchoice==tauntbearandbear_moved

36dead(Thebeargetspissedoffandchewsyourleg

off)

37elifchoice==opendoorandbear_moved

38gold_room()

39else

40print(Igotnoideawhatthatmeans)

41

42

43defcthulhu_room()

44print(HereyouseethegreatevilCthulhu)

45print(Heitwhateverstaresatyouandyougoinsane)

46print(Doyoufleeforyourlifeoreatyourhead)

47

48choice=input(gt)

49

50iffleeinchoice

51start()

52elifheadinchoice

53dead(Wellthatwastasty)

54else

55cthulhu_room()

56

57

58defdead(why)

59print(whyGoodjob)

60exit(0)

61

62defstart()

63print(Youareinadarkroom)

64print(Thereisadoortoyourrightandleft)

65print(Whichonedoyoutake)

66

67choice=input(gt)

68

69ifchoice==left

70bear_room()

71elifchoice==right

72cthulhu_room()

73else

74dead(Youstumblearoundtheroomuntilyoustarve)

75

76

77start()

WhatYouShouldSeeHerersquosmeplayingthegameClickheretoviewcodeimage

Exercise35Session

$python36ex35py

Youareinadarkroom

Thereisadoortoyourrightandleft

Whichonedoyoutake

gtleft

Thereisabearhere

Thebearhasabunchofhoney

Thefatbearisinfrontofanotherdoor

Howareyougoingtomovethebear

gttauntbear

Thebearhasmovedfromthedoor

Youcangothroughitnow

gtopendoor

ThisroomisfullofgoldHowmuchdoyoutake

gt1000

YougreedybastardGoodjob

StudyDrills1Drawamapofthegameandhowyouflowthroughit2Fixallofyourmistakesincludingspellingmistakes3Writecommentsforthefunctionsyoudonotunderstand4AddmoretothegameWhatcanyoudotobothsimplifyandexpandit5Thegold_roomhasaweirdwayofgettingyoutotypeanumberWhatareallthebugsinthiswayofdoingitCanyoumakeitbetterthanwhatIrsquovewrittenLookathowint()worksforclues

CommonStudentQuestionsHelpHowdoesthisprogramworkWhenyougetstuckunderstandingapieceofcodesimplywriteanEnglishcommentaboveeverylineexplainingwhatthatlinedoesKeepyourcommentsshortandsimilartothecodeTheneitherdiagramhowthecodeworksorwriteaparagraphdescribingitIfyoudothatyoursquollgetit

WhydidyouwritewhileTrueThatmakesaninfiniteloopWhatdoesexit(0)doOnmanyoperatingsystemsaprogramcanabortwithexit(0)andthenumberpassedinwillindicateanerrorornotIfyoudoexit(1)thenitwillbeanerrorbutexit(0)willbeagoodexitThereasonitrsquosbackwardfromnormalBooleanlogic(with0==False)isthatyoucanusedifferentnumbersto

indicatedifferenterrorresultsYoucandoexit(100)foradifferenterrorresultthanexit(2)orexit(1)

Whyisinput()sometimeswrittenasinput(gt)Theparametertoinputisastringthatitshouldprintasapromptbeforegettingtheuserrsquosinput

Exercise36DesigningandDebugging

Nowthatyouknowif-statementsIrsquomgoingtogiveyousomerulesforfor-loopsandwhile-loopsthatwillkeepyououtoftroubleIrsquomalsogoingtogiveyousometipsondebuggingsothatyoucanfigureoutproblemswithyourprogramFinallyyouwilldesignalittlegamesimilartothelastexercisebutwithaslighttwist

Rulesforif-statements1Everyif-statementmusthaveanelse2IfthiselseshouldneverrunbecauseitdoesnrsquotmakesensethenyoumustuseadiefunctionintheelsethatprintsoutanerrormessageanddiesjustlikewedidinthelastexerciseThiswillfindmanyerrors

3Nevernestif-statementsmorethantwodeepandalwaystrytodothemonedeep

4Treatif-statementslikeparagraphswhereeachif-elif-elsegroupingislikeasetofsentencesPutblanklinesbeforeandafter

5YourBooleantestsshouldbesimpleIftheyarecomplexmovetheircalculationstovariablesearlierinyourfunctionanduseagoodnameforthevariable

IfyoufollowthesesimplerulesyouwillstartwritingbettercodethanmostprogrammersGobacktothelastexerciseandseeifIfollowedalloftheserulesIfnotfixmymistakes

WarningNeverbeaslavetotherulesinreallifeFortrainingpurposesyouneedtofollowtheserulestomakeyourmindstrongbutinreallifesometimestheserulesarejuststupidIfyouthinkaruleisstupidtrynotusingit

RulesforLoops1Useawhile-looponlytoloopforeverandthatmeansprobablyneverThisonlyappliestoPythonotherlanguagesaredifferent

2Useafor-loopforallotherkindsofloopingespeciallyifthereisa

fixedorlimitednumberofthingstoloopover

TipsforDebugging1DonotusealdquodebuggerrdquoAdebuggerislikedoingafull-bodyscanonasickpersonYoudonotgetanyspecificusefulinformationandyoufindawholelotofinformationthatdoesnrsquothelpandisjustconfusing

2Thebestwaytodebugaprogramistouseprinttoprintoutthevaluesofvariablesatpointsintheprogramtoseewheretheygowrong

3MakesurepartsofyourprogramsworkasyouworkonthemDonotwritemassivefilesofcodebeforeyoutrytorunthemCodealittlerunalittlefixalittle

HomeworkNowwriteagamesimilartotheonethatIcreatedinthelastexerciseItcanbeanykindofgameyouwantinthesameflavorSpendaweekonitmakingitasinterestingaspossibleForStudyDrillsuselistsfunctionsandmodules(rememberthosefromExercise13)asmuchaspossibleandfindasmanynewpiecesofPythonasyoucantomakethegameworkBeforeyoustartcodingyoumustdrawamapforyourgameCreatetheroomsmonstersandtrapsthattheplayermustgothroughonpaperbeforeyoucodeOnceyouhaveyourmaptrytocodeitupIfyoufindproblemswiththemapthenadjustitandmakethecodematchThebestwaytoworkonapieceofsoftwareisinsmallchunkslikethis

1OnasheetofpaperoranindexcardwritealistoftasksyouneedtocompletetofinishthesoftwareThisisyourto-dolist

2Picktheeasiestthingyoucandofromyourlist3WriteoutEnglishcommentsinyoursourcefileasaguideforhowyouwouldaccomplishthistaskinyourcode

4WritesomeofthecodeundertheEnglishcomments5Quicklyrunyourscriptsoseeifthatcodeworked6Keepworkinginacycleofwritingsomecoderunningittotestitandfixingituntilitworks

7CrossthistaskoffyourlistthenpickyournexteasiesttaskandrepeatThisprocesswillhelpyouworkonsoftwareinamethodicalandconsistentmannerAsyouworkupdateyourlistbyremovingtasksyoudonrsquotreallyneedandaddingonesyoudo

andaddingonesyoudo

Exercise37SymbolReview

ItrsquostimetoreviewthesymbolsandPythonwordsyouknowandpickupafewmoreforthenextfewlessonsIhavewrittenoutallthePythonsymbolsandkeywordsthatareimportanttoknowInthislessontakeeachkeywordandfirsttrytowriteoutwhatitdoesfrommemoryNextsearchonlineforitandseewhatitreallydoesThismaybedifficultbecausesomeofthesearedifficulttosearchforbuttryanywayIfyougetoneofthesewrongfrommemorymakeanindexcardwiththecorrectdefinitionandtrytoldquocorrectrdquoyourmemoryFinallyuseeachoftheseinasmallPythonprogramorasmanyasyoucangetdoneThegoalistofindoutwhatthesymboldoesmakesureyougotitrightcorrectitifyoudidnotthenuseittolockitin

Keywords

DataTypesFordatatypeswriteoutwhatmakesupeachoneForexamplewithstringswriteouthowyoucreateastringFornumberswriteoutafewnumbers

StringEscapeSequencesForstringescapesequencesusetheminstringstomakesuretheydowhatyouthinktheydo

OldStyleStringFormatsSamethingforstringformatsusetheminsomestringstoknowwhattheydoOlderPython2codeusestheseformattingcharacterstodowhatf-stringsdoTrythemoutasanalternative

OperatorsSomeofthesemaybeunfamiliartoyoubutlookthemupanywayFindoutwhattheydoandifyoustillcanrsquotfigureitoutsaveitforlater

SpendaboutaweekonthisbutifyoufinishfasterthatrsquosgreatThepointistotrytogetcoverageonallthesesymbolsandmakesuretheyarelockedinyourheadWhatrsquosalsoimportantistofindoutwhatyoudonotknowsoyoucanfixitlater

ReadingCodeNowfindsomePythoncodetoreadYoushouldbereadinganyPythoncodeyoucanandtryingtostealideasthatyoufindYouactuallyshouldhaveenoughknowledgetobeabletoreadbutmaybenotunderstandwhatthecodedoesWhatthislessonteachesishowtoapplythingsyouhavelearnedtounderstandotherpeoplersquoscodeFirstprintoutthecodeyouwanttounderstandYesprintitoutbecauseyoureyesandbrainaremoreusedtoreadingpaperthancomputerscreensMakesureyouprintafewpagesatatimeSecondgothroughyourprintoutandtakenotesonthefollowing

1Functionsandwhattheydo2Whereeachvariableisfirstgivenavalue3AnyvariableswiththesamenamesindifferentpartsoftheprogramThesemaybetroublelater

4Anyif-statementswithoutelseclausesAretheyright5Anywhile-loopsthatmightnotend6Anypartsofcodethatyoucanrsquotunderstandforwhateverreason

ThirdonceyouhaveallofthismarkeduptrytoexplainittoyourselfbywritingcommentsasyougoExplainthefunctionshowtheyareusedwhatvariablesareinvolvedandanythingyoucantofigurethiscodeoutLastonallofthedifficultpartstracethevaluesofeachvariablelinebylinefunctionbyfunctionInfactdoanotherprintoutandwriteinthemarginthevalueofeachvariablethatyouneedtoldquotracerdquoOnceyouhaveagoodideaofwhatthecodedoesgobacktothecomputerandreaditagaintoseeifyoufindnewthingsKeepfindingmorecodeanddoingthisuntilyoudonotneedtheprintoutsanymore

StudyDrills1Findoutwhataldquoflowchartrdquoisanddrawafew2Ifyoufinderrorsincodeyouarereadingtrytofixthemandsendtheauthoryourchanges

3AnothertechniqueforwhenyouarenotusingpaperistoputcommentswithyournotesinthecodeSometimesthesecouldbecometheactualcommentstohelpthenextperson

CommonStudentQuestionsHowwouldIsearchforthesethingsonlineSimplyputldquopython36rdquobeforeanythingyouwanttofindForexampletofindldquoyieldrdquosearchforldquopython36yieldrdquo

Exercise38DoingThingstoLists

YouhavelearnedaboutlistsWhenyoulearnedaboutwhile-loopsyouldquoappendedrdquonumberstotheendofalistandprintedthemoutTherewerealsoStudyDrillswhereyouweresupposedtofindalltheotherthingsyoucandotolistsinthePythondocumentationThatwasawhilebacksoreviewthosetopicsifyoudonotknowwhatIrsquomtalkingaboutFounditRememberitGoodWhenyoudidthisyouhadalistandyouldquocalledrdquothefunctionappendonitHoweveryoumaynotreallyunderstandwhatrsquosgoingonsoletrsquosseewhatwecandotolistsWhenyouwritemystuffappend(hello)youareactuallysettingoffachainofeventsinsidePythontocausesomethingtohappentothemystufflistHerersquoshowitworks1PythonseesyoumentionedmystuffandlooksupthatvariableItmighthavetolookbackwardtoseeifyoucreateditwith=ifitisafunctionargumentorifitrsquosaglobalvariableEitherwayithastofindmystufffirst

2Onceitfindsmystuffitreadsthe(period)operatorandstartstolookatvariablesthatareapartofmystuffSincemystuffisalistitknowsthatmystuffhasabunchoffunctions

3ItthenhitsappendandcomparesthenametoallthenamesthatmystuffsaysitownsIfappendisinthere(itis)thenPythongrabsthattouse

4NextPythonseesthe((openparenthesis)andrealizesldquoOhheythisshouldbeafunctionrdquoAtthispointitcalls(runsorexecutes)thefunctionjustlikenormalbutitcallsthefunctionwithanextraargument

5ThatextraargumentismystuffIknowweirdrightButthatrsquoshowPythonworkssoitrsquosbesttojustrememberitandassumethatrsquostheresultWhathappensattheendofallthisisafunctioncallthatlookslikeappend(mystuffhello)insteadofwhatyoureadwhichismystuffappend(hello)

ForthemostpartyoudonothavetoknowthatthisisgoingonbutithelpswhenyougeterrormessagesfromPythonlikethisClickheretoviewcodeimage

$python36

gtgtgtclassThing(object)

deftest(message)

print(message)

gtgtgta=Thing()

gtgtgtatest(hello)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

TypeErrortest()takesexactly1argument(2given)

gtgtgtWhatwasallthatWellthisismetypingintothePythonshell

andshowingyousomemagicYouhavenrsquotseenclassyetbutwersquollget

intothatlaterFornowyouseehowPythonsaidtest()takesexactly

1argument(2given)IfyouseethisitmeansthatPythonchanged

atest(hello)totest(ahello)andthatsomewheresomeonemessed

upanddidnrsquotaddtheargumentfora

ThismightbealottotakeinbutwersquoregoingtospendafewexercisesgettingthisconceptfirminyourbrainTokickthingsoffherersquosanexercisethatmixesstringsandlistsforallkindsoffunClickheretoviewcodeimage

ex38py

1ten_things=ApplesOrangesCrowsTelephoneLightSugar

2

3print(Waittherearenot10thingsinthatlistLetsfix

that)

4

5stuff=ten_thingssplit()

6more_stuff=[DayNightSongFrisbee

7CornBananaGirlBoy]

8

9whilelen(stuff)=10

10next_one=more_stuffpop()

11print(Addingnext_one)

12stuffappend(next_one)

13print(fTherearelen(stuff)itemsnow)

14

15print(Therewegostuff)

16

17print(Letsdosomethingswithstuff)

18

19print(stuff[1])

20print(stuff[-1])whoafancy

21print(stuffpop())

22print(join(stuff))whatcool

23print(join(stuff[35]))superstellar

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Waittherearenot10thingsinthatlistLetsfixthat

AddingBoy

Thereare7itemsnow

AddingGirl

Thereare8itemsnow

AddingBanana

Thereare9itemsnow

AddingCorn

Thereare10itemsnow

Therewego[ApplesOrangesCrowsTelephoneLight

SugarBoyGirlBananaCorn]

Letsdosomethingswithstuff

Oranges

Corn

Corn

ApplesOrangesCrowsTelephoneLightSugarBoyGirlBanana

TelephoneLight

WhatListsCanDoLetrsquossayyouwanttocreateacomputergamebasedonGoFishIfyoudonrsquotknowwhatGoFishistakethetimenowtogoreaduponitontheinternetTodothisyouwouldneedtohavesomewayoftakingtheconceptofaldquodeckofcardsrdquoandputtingitintoyourPythonprogramYouthenhavetowritePythoncodethatknowshowtoworkthisimaginaryversionofadeckofcardssothatapersonplayingyourgamethinksthatitrsquosrealevenifitisnrsquotWhatyouneedisaldquodeckofcardsrdquostructureandprogrammerscallthiskindofthingadatastructureWhatrsquosadatastructureIfyouthinkaboutitadatastructureisjustaformalwaytostructure(organize)somedata(facts)ItreallyisthatsimpleEventhoughsomedatastructurescangetinsanelycomplexalltheyareisjustawaytostorefactsinsideaprogramsoyoucanaccessthemindifferentwaysTheystructuredataIrsquollbegettingintothismoreinthenextexercisebutlistsareoneofthemostcommondatastructuresprogrammersuseAlistisanorderedlistofthingsyouwanttostoreandaccessrandomlyorlinearlybyanindexWhatRememberwhatIsaidthoughjustbecauseaprogrammersaidldquolistisalistrdquodoesnrsquotmeanthatitrsquosanymorecomplexthanwhatalistalreadyisintherealworldLetrsquoslookatthedeckofcardsasanexampleofalist1Youhaveabunchofcardswithvalues

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard3Youcantakecardsoffthetopthebottomorthemiddleatrandom4Ifyouwanttofindaspecificcardyouhavetograbthedeckandgothroughitoneatatime

LetrsquoslookatwhatIsaidldquoAnorderedlistrdquoYesdeckofcardsisinorderwithafirstandalast

ldquoofthingsyouwanttostorerdquoYescardsarethingsIwanttostoreldquoandaccessrandomlyrdquoYesIcangrabacardfromanywhereinthedeck

ldquoorlinearlyrdquoYesifIwanttofindaspecificcardIcanstartatthebeginningandgoinorder

ldquobyanindexrdquoAlmostsincewithadeckofcardsifItoldyoutogetthecardatindex19yoursquodhavetocountuntilyoufoundthatoneInourPythonliststhecomputercanjustjumprighttoanyindexyougiveit

ThatisallalistdoesandthisshouldgiveyouawaytofigureoutconceptsinprogrammingEveryconceptinprogrammingusuallyhassomerelationshiptotherealworldAtleasttheusefulonesdoIfyoucanfigureoutwhattheanalogintherealworldisthenyoucanusethattofigureoutwhatthedatastructureshouldbeabletodo

WhentoUseListsYouusealistwheneveryouhavesomethingthatmatchesthelistdatastructurersquosusefulfeatures

1IfyouneedtomaintainorderRememberthisislistedordernotsortedorderListsdonotsortforyou

2IfyouneedtoaccessthecontentsrandomlybyanumberRememberthisisusingcardinalnumbersstartingat0

3Ifyouneedtogothroughthecontentslinearly(firsttolast)Rememberthatrsquoswhatfor-loopsarefor

Thisiswhenyouusealist

StudyDrills1TakeeachfunctionthatiscalledandgothroughthestepsforfunctioncallstotranslatethemtowhatPythondoesForexamplemore_stuffpop()ispop(more_stuff)

2TranslatethesetwowaystoviewthefunctioncallsinEnglishForexamplemore_stuffpop()readsasldquoCallpoponmore_stuffrdquoMeanwhilepop(more_stuff)meansldquoCallpopwithargumentmore_stuffrdquoUnderstandhowtheyarereallythesamething

3Goreadaboutobject-orientedprogrammingonlineConfusedIwastooDonotworryYouwilllearnenoughtobedangerousandyoucanslowlylearnmorelater

4ReaduponwhataclassisinPythonDonotreadabouthowotherlanguagesusethewordldquoclassrdquoThatwillonlymessyouup

5DonotworryIfyoudonothaveanyideawhatIrsquomtalkingaboutProgrammersliketofeelsmartsotheyinventedobject-orientedprogrammingnameditOOPandthenuseditwaytoomuchIfyouthinkthatrsquoshardyoushouldtrytouseldquofunctionalprogrammingrdquo

6Find10examplesofthingsintherealworldthatwouldfitinalistTrywritingsomescriptstoworkwiththem

CommonStudentQuestionsDidnrsquotyousaytonotusewhile-loopsYessojustremembersometimesyoucanbreaktherulesifyouhaveagoodreasonOnlyidiotsareslavestorulesallthetime

Whydoesjoin(stuff)notworkThewaythedocumentationforjoiniswrittendoesnrsquotmakesenseItdoesnotworklikethatandisinsteadamethodyoucallontheinsertedstringtoputbetweenthelisttobejoinedRewriteitlikejoin(stuff)

Whydidyouuseawhile-loopTryrewritingitwithafor-loopandseeifthatrsquoseasier

Whatdoesstuff[35]doThatextractsaldquoslicerdquofromthestufflistthatisfromelement3toelement4meaningitdoesnotincludeelement5Itrsquossimilartohowrange(35)wouldwork

Exercise39DictionariesOhLovelyDictionaries

YouarenowgoingtolearnabouttheDictionarydatastructureinPythonADictionary(ordict)isawaytostoredatajustlikealistbutinsteadofusingonlynumberstogetthedatayoucanusealmostanythingThisletsyoutreatadictlikeitrsquosadatabaseforstoringandorganizingdataLetrsquoscomparewhatdictscandotowhatlistscandoYouseealistletsyoudothisClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtthings=[abcd]

gtgtgtprint(things[1])

b

gtgtgtthings[1]=z

gtgtgtprint(things[1])

z

gtgtgtthings

[azcd]

YoucanusenumberstoindexintoalistmeaningyoucanusenumberstofindoutwhatrsquosinlistsYoushouldknowthisaboutlistsbynowbutmakesureyouunderstandthatyoucanonlyusenumberstogetitemsoutofalistAdictletsyouuseanythingnotjustnumbersYesadictassociatesonethingtoanothernomatterwhatitisTakealookClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtstuff=nameZedage39height612+2

gtgtgtprint(stuff[name])

Zed

gtgtgtprint(stuff[age])

39

gtgtgtprint(stuff[height])

74

gtgtgtstuff[city]=SF

gtgtgtprint(stuff[city])

SF

YouwillseethatinsteadofjustnumberswersquoreusingstringstosaywhatwewantfromthestuffdictionaryWecanalsoputnewthingsintothedictionary

withstringsItdoesnrsquothavetobestringsthoughWecanalsodothisExercise39PythonSession

gtgtgtstuff[1]=Wow

gtgtgtstuff[2]=Neato

gtgtgtprint(stuff[1])

Wow

gtgtgtprint(stuff[2])

NeatoInthiscodeIusednumbersandthenyoucanseethereare

numbersandstringsaskeysinthedictwhenIprintitIcoulduse

anythingWellalmostbutjustpretendyoucanuseanythingfornow

OfcourseadictionarythatyoucanonlyputthingsinisprettystupidsoherersquoshowyoudeletethingswiththedelkeywordClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtdelstuff[city]

gtgtgtdelstuff[1]

gtgtgtdelstuff[2]

gtgtgtstuff

nameZedage39height74

ADictionaryExampleWersquollnowdoanexercisethatyoumuststudyverycarefullyIwantyoutotypethiscodeinandtrytounderstandwhatrsquosgoingonTakenoteofwhenyouputthingsinadictgetthemfromahashandalltheoperationsyouuseNoticehowthisexampleismappingstatestotheirabbreviationsandthentheabbreviationstocitiesinthestatesRemembermapping(orassociating)isthekeyconceptinadictionaryClickheretoviewcodeimage

ex39py

1createamappingofstatetoabbreviation

2states=

3OregonOR

4FloridaFL

5CaliforniaCA

6NewYorkNY

7MichiganMI

8

9

10createabasicsetofstatesandsomecitiesinthem

11cities=

12CASanFrancisco

13MIDetroit

14FLJacksonville

15

16

17addsomemorecities

18cities[NY]=NewYork

19cities[OR]=Portland

20

21printoutsomecities

22print(-10)

23print(NYStatehascities[NY])

24print(ORStatehascities[OR])

25

26printsomestates

27print(-10)

28print(Michigansabbreviationisstates[Michigan])

29print(Floridasabbreviationisstates[Florida])

30

31doitbyusingthestatethencitiesdict

32print(-10)

33print(Michiganhascities[states[Michigan]])

34print(Floridahascities[states[Florida]])

35

36printeverystateabbreviation

37print(-10)

38forstateabbrevinlist(statesitems())

39print(fstateisabbreviatedabbrev)

40

41printeverycityinstate

42print(-10)

43forabbrevcityinlist(citiesitems())

44print(fabbrevhasthecitycity)

45

46nowdobothatthesametime

47print(-10)

48forstateabbrevinlist(statesitems())

49print(fstatestateisabbreviatedabbrev)

50print(fandhascitycities[abbrev])

51

52print(-10)

53safelygetaabbreviationbystatethatmightnotbethere

54state=statesget(Texas)

55

56ifnotstate

57print(SorrynoTexas)

58

59getacitywithadefaultvalue

60city=citiesget(TXDoesNotExist)

61print(fThecityforthestateTXiscity)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise39Session

$python36ex39py

----------

NYStatehasNewYork

ORStatehasPortland

----------

MichigansabbreviationisMI

FloridasabbreviationisFL

----------

MichiganhasDetroit

FloridahasJacksonville

----------

OregonisabbreviatedOR

FloridaisabbreviatedFL

CaliforniaisabbreviatedCA

NewYorkisabbreviatedNY

MichiganisabbreviatedMI

----------

CAhasthecitySanFrancisco

MIhasthecityDetroit

FLhasthecityJacksonville

NYhasthecityNewYork

ORhasthecityPortland

----------

OregonstateisabbreviatedOR

andhascityPortland

FloridastateisabbreviatedFL

andhascityJacksonville

CaliforniastateisabbreviatedCA

andhascitySanFrancisco

NewYorkstateisabbreviatedNY

andhascityNewYork

MichiganstateisabbreviatedMI

andhascityDetroit

----------

SorrynoTexas

ThecityforthestateTXisDoesNotExist

WhatDictionariesCanDo

WhatDictionariesCanDoAdictionaryisanotherexampleofadatastructureandlikealistitisoneofthemostcommonlyuseddatastructuresinprogrammingAdictionaryisusedtomaporassociatethingsyouwanttostoretokeysyouneedtogetthemAgainprogrammersdonrsquotuseatermlikeldquodictionaryrdquoforsomethingthatdoesnrsquotworklikeanactualdictionaryfullofwordssoletrsquosusethatasourrealworldexampleLetrsquossayyouwanttofindoutwhatthewordldquohonorificabilitudinitatibusrdquomeansTodayyouwouldsimplycopy-pastethatwordintoasearchengineandthenfindouttheanswerandwecouldsayasearchengineislikeareallyhugesupercomplexversionoftheOxfordEnglishDictionary(OED)Beforesearchengineswhatyouwoulddoisthis1GotoyourlibraryandgetldquothedictionaryrdquoLetrsquossayitrsquostheOED

2YouknowldquohonorificabilitudinitatibusrdquostartswiththeletterldquoHrdquosoyoulookonthesideofthebookforthelittletabthathasldquoHrdquoonit

3Skimthepagesuntilyouareclosetowhereldquohonrdquostarts4SkimafewmorepagesuntilyoufindldquohonorificabilitudinitatibusrdquoorhitthebeginningoftheldquohprdquowordsandrealizethiswordisnrsquotintheOED

5Onceyoufindtheentryyoureadthedefinitiontofigureoutwhatitmeans

ThisprocessisnearlyexactlythewayadictworksandyouarebasicallyldquomappingrdquothewordldquohonorificabilitudinitatibusrdquotoitsdefinitionAdictinPythonisjustlikeadictionaryintherealworldsuchastheOED

StudyDrills1Dothissamekindofmappingwithcitiesandstatesregionsinyourcountryorsomeothercountry

2FindthePythondocumentationfordictionariesandtrytodoevenmorethingstothem

3FindoutwhatyoucanrsquotdowithdictionariesAbigoneisthattheydonothaveordersotryplayingwiththat

CommonStudentQuestionsWhatisthedifferencebetweenalistandadictionaryAlistisforanorderedlistofitemsAdictionary(ordict)isformatchingsomeitems(calledldquokeysrdquo)tootheritems(calledldquovaluesrdquo)

WhatwouldIuseadictionaryforWhenyouhavetotakeonevalueandldquolookuprdquoanothervalueInfactyoucouldcalldictionariesldquolookuptablesrdquo

WhatwouldIusealistforUsealistforanysequenceofthingsthatneedstobeinorderandyouonlyneedtolookthemupbyanumericindex

WhatifIneedadictionarybutIneedittobeinorderTakealookatthecollectionsOrderedDictdatastructureinPythonSearchforitonlinetofindthedocumentation

Exercise40ModulesClassesandObjects

Pythoniscalledanldquoobject-orientedprogramminglanguagerdquoThismeansthereisaconstructinPythoncalledaclassthatletsyoustructureyoursoftwareinaparticularwayUsingclassesyoucanaddconsistencytoyourprogramssothattheycanbeusedinacleanerwayAtleastthatrsquosthetheoryIamnowgoingtoteachyouthebeginningsofobject-orientedprogrammingclassesandobjectsusingwhatyoualreadyknowaboutdictionariesandmodulesMyproblemisthatobject-orientedprogramming(OOP)isjustplainweirdYouhavetostrugglewiththistrytounderstandwhatIsayheretypeinthecodeandinthenextexerciseIrsquollhammeritinHerewego

ModulesAreLikeDictionariesYouknowhowadictionaryiscreatedandusedandthatitisawaytomaponethingtoanotherThatmeansifyouhaveadictionarywithakeyldquoapplerdquoandyouwanttogetitthenyoudothisClickheretoviewcodeimage

ex40apy

1mystuff=appleIAMAPPLES

2print(mystuff[apple])

KeepthisideaofldquogetXfromYrdquoinyourheadandnowthinkaboutmodulesYoursquovemadeafewsofarandyoushouldknowtheyare1APythonfilewithsomefunctionsorvariablesinit

2Whichyoucanimport3Andaccessthefunctionsorvariablesofwiththe(dot)operator

ImagineIhaveamodulethatIdecidetonamemystuffpyandIputafunctioninitcalledappleHerersquosthemodulemystuffpyClickheretoviewcodeimage

ex40apy

1thisgoesinmystuffpy

2defapple()

3print(IAMAPPLES)OnceIhavethiscodeIcanusethe

moduleMyStuffwithimportandthenaccesstheapplefunction

ex40apy

1importmystuff

2mystuffapple()Icouldalsoputavariableinitnamed

tangerineClickheretoviewcodeimage

ex40apy

1defapple()

2print(IAMAPPLES)

3

4thisisjustavariable

5tangerine=Livingreflectionofadream

Icanaccessthatthesamewayex40apy

1importmystuff

2

3mystuffapple()

4print(mystufftangerine)Referbacktothedictionaryandyou

shouldstarttoseehowthisissimilartousingadictionarybut

thesyntaxisdifferentLetrsquoscompareClickheretoviewcodeimage

ex40apy

1mystuff[apple]getapplefromdict

2mystuffapple()getapplefromthemodule

3mystufftangerinesamethingitsjustavariableThismeans

wehaveaverycommonpatterninPython1Takeakey=valuestyle

container

2GetsomethingoutofitbythekeyrsquosnameInthecaseofthedictionarythekeyisastringandthesyntaxis[key]InthecaseofthemodulethekeyisanidentifierandthesyntaxiskeyOtherthanthattheyarenearlythesamething

ClassesAreLikeModulesYoucanthinkaboutamoduleasaspecializeddictionarythatcanstorePythoncodesoyoucanaccessitwiththeoperatorPythonalsohasanotherconstructthatservesasimilarpurposecalledaclassAclassisawaytotakeagroupingof

functionsanddataandplacetheminsideacontainersoyoucanaccessthemwiththe(dot)operatorIfIweretocreateaclassjustlikethemystuffmoduleIrsquoddosomethinglikethisClickheretoviewcodeimage

ex40apy

1classMyStuff(object)

2

3def__init__(self)

4selftangerine=Andnowathousandyearsbetween

5

6defapple(self)

7print(IAMCLASSYAPPLES)Thatlookscomplicated

comparedtomodulesandthereisdefinitelyalotgoingonby

comparisonbutyoushouldbeabletomakeouthowthisislikea

ldquomini-modulerdquowithMyStuffhavinganapple()functioninitWhatis

probablyconfusingisthe__init__()functionanduseof

selftangerineforsettingthetangerineinstancevariable

HerersquoswhyclassesareusedinsteadofmodulesYoucantakethisMyStuffclassanduseittocraftmanyofthemmillionsatatimeifyouwantandeachonewonrsquotinterferewitheachotherWhenyouimportamodulethereisonlyonefortheentireprogramunlessyoudosomemonsterhacksBeforeyoucanunderstandthisthoughyouneedtoknowwhatanldquoobjectrdquoisandhowtoworkwithMyStuffjustlikeyoudowiththemystuffpymodule

ObjectsAreLikeImportIfaclassislikealdquomini-modulerdquothentherehastobeaconceptsimilartoimportbutforclassesThatconceptiscalledldquoinstantiaterdquowhichisjustafancyobnoxiousoverlysmartwaytosayldquocreaterdquoWhenyouinstantiateaclasswhatyougetiscalledanobjectYouinstantiate(create)aclassbycallingtheclasslikeitrsquosafunctionlikethisex40apy

1thing=MyStuff()

2thingapple()

3print(thingtangerine)Thefirstlineistheldquoinstantiaterdquo

operationanditrsquosalotlikecallingafunctionHoweverPython

coordinatesasequenceofeventsforyoubehindthescenesIrsquollgo

throughthesestepsusingtheprecedingcodeforMyStuff1Python

looksforMyStuff()andseesthatitisaclassyoursquovedefined

2Pythoncraftsanemptyobjectwithallthefunctionsyoursquovespecifiedintheclassusingdef

3Pythonthenlookstoseeifyoumadealdquomagicrdquo__init__functionandifyouhaveitcallsthatfunctiontoinitializeyournewlycreatedemptyobject

4IntheMyStufffunction__init__youthengetthisextravariableselfwhichisthatemptyobjectPythonmadeforyouandyoucansetvariablesonitjustlikeyouwouldwithamoduledictionaryorotherobject

5Inthiscaseyousetselftangerinetoasonglyricandthenyoursquoveinitializedthisobject

6NowPythoncantakethisnewlymintedobjectandassignittothethingvariableforyoutoworkwith

ThatrsquosthebasicsofhowPythondoesthisldquomini-importrdquowhenyoucallaclasslikeafunctionRememberthatthisisnotgivingyoutheclassbutinsteadisusingtheclassasablueprintforbuildingacopyofthattypeofthingKeepinmindthatIrsquomgivingyouaslightlyinaccurateideaofhowtheseworksothatyoucanstarttobuildupanunderstandingofclassesbasedonwhatyouknowaboutmodulesThetruthisclassesandobjectssuddenlydivergefrommodulesatthispointIfIwerebeingtotallyhonestIrsquodsaysomethingmorelikethisbullClassesarelikeblueprintsordefinitionsforcreatingnewmini-modules

bullInstantiationishowyoumakeoneofthesemini-modulesandimportitatthesametimeldquoInstantiaterdquojustmeanstocreateanobjectfromtheclass

bullTheresultingcreatedmini-moduleiscalledanobjectandyouthenassignittoavariabletoworkwithit

Atthispointobjectsbehavedifferentlyfrommodulesandthisshouldonlyserveasawayforyoutobridgeovertounderstandingclassesandobjects

GettingThingsfromThingsInowhavethreewaystogetthingsfromthingsClickheretoviewcodeimage

ex40apy

1dictstyle

2mystuff[apples]

3

4modulestyle

5mystuffapples()

6print(mystufftangerine)

7

8classstyle

9thing=MyStuff()

10thingapples()

11print(thingtangerine)

AFirstClassExampleYoushouldstartseeingthesimilaritiesinthesethreekey=valuecontainertypesandprobablyhaveabunchofquestionsHangonwiththequestionsasthenextexercisewillhammerhomeyourldquoobject-orientedvocabularyrdquoInthisexerciseIjustwantyoutotypeinthiscodeandgetitworkingsothatyouhavesomeexperiencebeforemovingonClickheretoviewcodeimage

ex40py

1classSong(object)

2

3def__init__(selflyrics)

4selflyrics=lyrics

5

6defsing_me_a_song(self)

7forlineinselflyrics

8print(line)

9

10happy_bday=Song([Happybirthdaytoyou

11Idontwanttogetsued

12SoIllstoprightthere])

13

14bulls_on_parade=Song([Theyrallyaroundthafamily

15Withpocketsfullofshells])

16

17happy_bdaysing_me_a_song()

18

19bulls_on_paradesing_me_a_song()

WhatYouShouldSee

Exercise40Session

$python36ex40py

Happybirthdaytoyou

Idontwanttogetsued

SoIllstoprightthere

Theyrallyaroundthafamily

Withpocketsfullofshells

StudyDrills1Writesomemoresongsusingthisandmakesureyouunderstandthatyoursquorepassingalistofstringsasthelyrics

2Putthelyricsinaseparatevariablethenpassthatvariabletotheclasstouseinstead

3SeeifyoucanhackonthisandmakeitdomorethingsDonrsquotworryifyouhavenoideahowjustgiveitatryandseewhathappensBreakittrashitthrashityoucanrsquothurtit

4Searchonlineforldquoobject-orientedprogrammingrdquoandtrytooverflowyourbrainwithwhatyoureadDonrsquotworryifitmakesabsolutelynosensetoyouHalfofthatstuffmakesnosensetometoo

CommonStudentQuestionsWhydoIneedselfwhenImake__init__orotherfunctionsforclassesIfyoudonrsquothaveselfthencodelikecheese=FrankisambiguousThatcodeisnrsquotclearaboutwhetheryoumeantheinstancersquoscheeseattributeoralocalvariablenamedcheeseWithselfcheese=Frankitrsquosveryclearyoumeantheinstanceattributeselfcheese

Exercise41LearningtoSpeakObject-Oriented

InthisexerciseIrsquomgoingtoteachyouhowtospeakldquoobject-orientedrdquoWhatIrsquolldoisgiveyouasmallsetofwordswithdefinitionsyouneedtoknowThenIrsquollgiveyouasetofsentenceswithholesinthemthatyoursquollhavetounderstandFinallyIrsquomgoingtogiveyoualargesetofexercisesthatyouhavetocompletetomakethesesentencessolidinyourvocabulary

WordDrillsclassTellPythontomakeanewtypeofthingobjectTwomeaningsthemostbasictypeofthingandanyinstanceofsomething

instanceWhatyougetwhenyoutellPythontocreateaclassdefHowyoudefineafunctioninsideaclassselfInsidethefunctionsinaclassselfisavariablefortheinstanceobjectbeingaccessed

inheritanceTheconceptthatoneclasscaninherittraitsfromanotherclassmuchlikeyouandyourparents

compositionTheconceptthataclasscanbecomposedofotherclassesaspartsmuchlikehowacarhaswheels

attributeApropertyclasseshavethatarefromcompositionandareusuallyvariables

is-aAphrasetosaythatsomethinginheritsfromanotherasinaldquosalmonrdquois-ardquofishldquo

has-aAphrasetosaythatsomethingiscomposedofotherthingsorhasatraitasinldquoasalmonhas-amouthrdquo

TakesometimetomakeflashcardsforthesetermsandmemorizethemAsusualthiswonrsquotmaketoomuchsenseuntilafteryouarefinishedwiththisexercisebutyouneedtoknowthebasewordsfirst

PhraseDrillsNextIhavealistofPythoncodesnippetsontheleftandtheEnglishsentencesforthem

classX(Y)ldquoMakeaclassnamedXthatis-aYrdquo

classX(object)def__init__(selfJ)ldquoclassXhas-a__init__thattakesselfandJparametersrdquo

classX(object)defM(selfJ)ldquoclassXhas-afunctionnamedMthattakesselfandJparametersrdquo

foo=X()ldquoSetfootoaninstanceofclassXrdquofooM(J)ldquoFromfoogettheMfunctionandcallitwithparametersselfJrdquo

fooK=QldquoFromfoogettheKattributeandsetittoQrdquoIneachofthesewhereyouseeXYMJKQandfooyoucantreatthoselikeblankspotsForexampleIcanalsowritethesesentencesasfollows1ldquoMakeaclassnamedthatis-aYrdquo

2ldquoclasshas-a__init__thattakesselfandparametersrdquo3ldquoclasshas-afunctionnamedthattakesselfandparametersrdquo4ldquoSettoaninstanceofclassrdquo5ldquoFromgetthefunctionandcallitwithself=andparametersrdquo

6ldquoFromgettheattributeandsetittordquoAgainwritetheseonsomeflashcardsanddrillthemPutthePythoncodesnippetonthefrontandthesentenceonthebackYouhavetobeabletosaythesentenceexactlythesameeverytimewheneveryouseethatformNotsortofthesamebutexactlythesame

CombinedDrillsThefinalpreparationforyouistocombinethewordsdrillswiththephrasedrillsWhatIwantyoutodoforthisdrillisthis

1Takeaphrasecardanddrillit2Flipitoverandreadthesentenceandforeachwordinthesentencethatisinyourwordsdrillsgetthatcard

3Drillthosewordsforthatsentence4Keepgoinguntilyouareboredthentakeabreakanddoitagain

AReadingTestInowhavealittlePythonhackscriptthatwilldrillyouonthesewordsyouknowinaninfinitemannerThisisasimplescriptyoushouldbeabletofigureoutandtheonlythingitdoesisusealibrarycalledurllibtodownloadalist

ofwordsIhaveHerersquosthescriptwhichyoushouldenterintooop_testpytoworkwithitClickheretoviewcodeimage

ex41py

1importrandom

2fromurllibrequestimporturlopen

3importsys

4

5WORD_URL=httplearncodethehardwayorgwordstxt

6WORDS=[]

7

8PHRASES=

9class()

10Makeaclassnamedthatis-a

11class(object)ntdef__init__(self)

12classhas-a__init__thattakesselfand

params

13class(object)ntdef(self)

14classhas-afunctionthattakesselfand

params

15=()

16Settoaninstanceofclass

17()

18Fromgetthefunctioncallitwithparamsself

19=

20Fromgettheattributeandsetitto

21

22

23dotheywanttodrillphrasesfirst

24iflen(sysargv)==2andsysargv[1]==english

25PHRASE_FIRST=True

26else

27PHRASE_FIRST=False

28

29loadupthewordsfromthewebsite

30forwordinurlopen(WORD_URL)readlines()

31WORDSappend(str(wordstrip()encoding=utf-8))

32

33

34defconvert(snippetphrase)

35class_names=[wcapitalize()forwin

36randomsample(WORDSsnippetcount())]

37other_names=randomsample(WORDSsnippetcount())

38results=[]

39param_names=[]

40

41foriinrange(0snippetcount())

42param_count=randomrandint(13)

43param_namesappend(join(

44randomsample(WORDSparam_count)))

45

46forsentenceinsnippetphrase

47result=sentence[]

48

49fakeclassnames

50forwordinclass_names

51result=resultreplace(word1)

52

53fakeothernames

54forwordinother_names

55result=resultreplace(word1)

56

57fakeparameterlists

58forwordinparam_names

59result=resultreplace(word1)

60

61resultsappend(result)

62

63returnresults

64

65

66keepgoinguntiltheyhitCTRL-D

67try

68whileTrue

69snippets=list(PHRASESkeys())

70randomshuffle(snippets)

71

72forsnippetinsnippets

73phrase=PHRASES[snippet]

74questionanswer=convert(snippetphrase)

75ifPHRASE_FIRST

76questionanswer=answerquestion

77

78print(question)

79

80input(lt)

81print(fANSWERanswernn)

82exceptEOFError

83print(nBye)Runthisscriptandtrytotranslatethe

ldquoobject-orientedphrasesrdquointoEnglishtranslationsYoushouldsee

thatthePHRASESdicthasbothformsandthatyoujusthavetoenter

thecorrectone

PracticeEnglishtoCode

PracticeEnglishtoCodeNextyoushouldrunthescriptwiththeldquoenglishrdquooptionsothatyoudrilltheinverseoperation

$pythonoop_testpyenglishRememberthatthesephrasesareusing

nonsensewordsPartoflearningtoreadcodewellistostopplacing

somuchmeaningonthenamesusedforvariablesandclassesToo

oftenpeoplewillreadawordlikeldquoCorkrdquoandsuddenlygetderailed

becausethatwordwillconfusethemaboutthemeaningIntheabove

exampleldquoCorkrdquoisjustanarbitrarynamechosenforaclassDonrsquot

placeanyothermeaningonitandinsteadtreatitlikethepatterns

Irsquovegivenyou

ReadingMoreCodeYouarenowtogoonanewquesttoreadevenmorecodetoreadthephrasesyoujustlearnedinthecodeyoureadYouwilllookforallthefileswithclassesandthendothefollowing

1Foreachclassgiveitsnameandwhatotherclassesitinheritsfrom2Underthatlisteveryfunctionithasandtheparameterstheytake3Listalloftheattributesitusesonitsself4Foreachattributegivetheclassthisattributeis

ThegoalistogothroughrealcodeandstartlearningtoldquopatternmatchrdquothephrasesyoujustlearnedagainsthowtheyrsquoreusedIfyoudrillthisenoughyoushouldstarttoseethesepatternsshoutatyouinthecodewhereasbeforetheyjustseemedlikevagueblankspotsyoudidnrsquotknow

CommonStudentQuestionsWhatdoesresult=sentence[]doThatrsquosaPythonwayofcopyingalistYoursquoreusingthelistslicesyntax[]toeffectivelymakeaslicefromtheveryfirstelementtotheverylastone

ThisscriptishardtogetrunningBythispointyoushouldbeabletotypethisinandgetitworkingItdoeshaveafewlittletrickshereandtherebuttherersquosnothingcomplexaboutitJustdoallthethingsyoursquovelearnedsofartodebugscriptsTypeeachlineinconfirmthatitrsquosexactlylikemineandresearchanythingyoudonrsquotknowonline

ItrsquosstilltoohardYoucandothisTakeitveryslowcharacterbycharacterifyouhavetobuttypeitinexactlyandfigureoutwhatitdoes

Exercise42Is-AHas-AObjectsandClasses

AnimportantconceptthatyouhavetounderstandisthedifferencebetweenaclassandanobjectTheproblemisthereisnorealldquodifferencerdquobetweenaclassandanobjectTheyareactuallythesamethingatdifferentpointsintimeIwilldemonstratewithaZenkoanWhatisthedifferencebetweenafishandasalmonDidthatquestionsortofconfuseyouReallysitdownandthinkaboutitforaminuteImeanafishandasalmonaredifferentbutwaittheyarethesamethingrightAsalmonisakindoffishsoImeanitrsquosnotdifferentButatthesametimeasalmonisaparticulartypeoffishsoitrsquosactuallydifferentfromallotherfishThatrsquoswhatmakesitasalmonandnotahalibutSoasalmonandafisharethesamebutdifferentWeirdThisquestionisconfusingbecausemostpeopledonotthinkaboutrealthingsthiswaybuttheyintuitivelyunderstandthemYoudonotneedtothinkaboutthedifferencebetweenafishandasalmonbecauseyouknowhowtheyarerelatedYouknowasalmonisakindoffishandthatthereareotherkindsoffishwithouthavingtounderstandthatLetrsquostakeitonestepfurtherLetrsquossayyouhaveabucketfullofthreesalmonandbecauseyouareanicepersonyouhavedecidedtonamethemFrankJoeandMaryNowthinkaboutthisquestionWhatisthedifferencebetweenMaryandasalmonAgainthisisaweirdquestionbutitrsquosabiteasierthanthefishversussalmonquestionYouknowthatMaryisasalmonsoshersquosnotreallydifferentShersquosjustaspecificldquoinstancerdquoofasalmonJoeandFrankarealsoinstancesofsalmonWhatdoImeanwhenIsayinstanceImeantheywerecreatedfromsomeothersalmonandnowrepresentarealthingthathassalmon-likeattributesNowforthemind-bendingideaFishisaclassandSalmonisaclassandMaryisanobjectThinkaboutthatforasecondLetrsquosbreakitdownslowlyandseeifyougetitAfishisaclassmeaningitrsquosnotarealthingbutratherawordweattachtoinstancesofthingswithsimilarattributesGotfinsGotgillsLivesinwaterAlrightitrsquosprobablyafishSomeonewithaPhDthencomesalongandsaysldquoNomyyoungfriendthisfishisactuallySalmosalaraffectionatelyknownasasalmonrdquoThisprofessorhasjustclarifiedthefishfurtherandmadeanewclasscalledldquoSalmonrdquothathas

morespecificattributesLongernosereddishfleshbiglivesintheoceanorfreshwatertastyProbablyasalmonFinallyacookcomesalongandtellsthePhDldquoNoyouseethisSalmonrighthereIrsquollcallherMaryandIrsquomgoingtomakeatastyfilletoutofherwithanicesaucerdquoNowyouhavethisinstanceofasalmon(whichalsoisaninstanceofafish)namedMaryturnedintosomethingrealthatisfillingyourbellyIthasbecomeanobjectThereyouhaveitMaryisakindofsalmonthatisakindoffishmdashobjectisaclassisaclass

HowThisLooksinCodeThisisaweirdconceptbuttobeveryhonestyouonlyhavetoworryaboutitwhenyoumakenewclassesandwhenyouuseaclassIwillshowyoutwotrickstohelpyoufigureoutwhethersomethingisaclassoranobjectFirstyouneedtolearntwocatchphrasesldquois-ardquoandldquohas-ardquoYouusethephraseis-awhenyoutalkaboutobjectsandclassesbeingrelatedtoeachotherbyaclassrelationshipYouusehas-awhenyoutalkaboutobjectsandclassesthatarerelatedonlybecausetheyreferenceeachotherNowgothroughthispieceofcodeandreplaceeachcommentwithacommentthatsayswhetherthenextlinerepresentsanis-aorahas-arelationshipandwhatthatrelationshipisInthebeginningofthecodeIrsquovelaidoutafewexamplessoyoujusthavetowritetheremainingonesRememberis-aistherelationshipbetweenfishandsalmonwhilehas-aistherelationshipbetweensalmonandgillsClickheretoviewcodeimage

ex42py

1Animalis-aobject(yessortofconfusing)lookatthe

extracredit

2classAnimal(object)

3pass

4

5

6classDog(Animal)

7

8def__init__(selfname)

9

10selfname=name

11

12

13classCat(Animal)

14

15def__init__(selfname)

16

17selfname=name

18

19

20classPerson(object)

21

22def__init__(selfname)

23

24selfname=name

25

26Personhas-apetofsomekind

27selfpet=None

28

29

30classEmployee(Person)

31

32def__init__(selfnamesalary)

33hmmwhatisthisstrangemagic

34super(Employeeself)__init__(name)

35

36selfsalary=salary

37

38

39classFish(object)

40pass

41

42

43classSalmon(Fish)

44pass

45

46

47classHalibut(Fish)

48pass

49

50

51roveris-aDog

52rover=Dog(Rover)

53

54

55satan=Cat(Satan)

56

57

58mary=Person(Mary)

59

60

61marypet=satan

62

63

64frank=Employee(Frank120000)

65

66

67frankpet=rover

68

69

70flipper=Fish()

71

72

73crouse=Salmon()

74

75

76harry=Halibut()

AboutclassName(object)InPython3youdonotneedtoaddthe(object)afterthenameoftheclassbutthePythoncommunitybelievesinldquoexplicitisbetterthanimplicitrdquosoIandotherPythonexpertshavedecidedtoincludeitYoumayrunintocodethatdoesnothave(object)aftersimpleclassesandthoseclassesareperfectlyfineandwillworkwithclassesyoucreatethatdohave(object)AtthispointitissimplyextradocumentationandhasnoimpactonhowyourclassesworkInPython2therewasadifferencebetweenthetwotypesofclassesbutnowyoudonrsquothavetoworryaboutitTheonlytrickyparttousing(object)involvesthementalgymnasticsofsayingldquoclassNameisaclassoftypeobjectrdquoThatmaysoundconfusingtoyounowsinceitrsquosaclassthatrsquosanameobjectthatrsquosaclassbutdonrsquotfeelbadaboutthatJustthinkofclassName(object)assayingldquothisisabasicsimpleclassrdquoandyoursquollbefineFinallyinthefuturethestylesandtastesofPythonprogrammersmaychangeandthisexplicituseof(object)mightbeseenasasignthatyouareabadprogrammerIfthathappenssimplystopusingitortellthemldquoPythonZensaysexplicitisbetterthanimplicitrdquo

StudyDrills1ResearchwhyPythonaddedthisstrangeobjectclassandwhatthatmeans2Isitpossibletouseaclasslikeitrsquosanobject3FillouttheanimalsfishandpeopleinthisexercisewithfunctionsthatmakethemdothingsSeewhathappenswhenfunctionsareinaldquobase

classrdquolikeAnimalversusinsayDog4Findotherpeoplersquoscodeandworkoutalltheis-aandhas-arelationships5Makesomenewrelationshipsthatarelistsanddictionariessoyoucanalsohaveldquohas-manyrdquorelationships

6Doyouthinktherersquossuchthingasanldquois-manyrdquorelationshipReadaboutldquomultipleinheritancerdquothenavoiditifyoucan

CommonStudentQuestionsWhatarethesecommentsforThoseareldquofill-in-the-blankrdquocommentsthatyouaresupposedtofillinwiththerightis-aandhas-aconceptsReadthisexerciseagainandlookattheothercommentstoseewhatImean

Whatisthepointofselfpet=NoneThatmakessurethattheselfpetattributeofthatclassissettoadefaultofNone

Whatdoessuper(Employeeself)__init__(name)doThatrsquoshowyoucanrunthe__init__methodofaparentclassreliablySearchforldquopython36superrdquoandreadthevariousadviceonitbeingevilandgoodforyou

Exercise43BasicObject-OrientedAnalysisandDesign

IrsquomgoingtodescribeaprocesstousewhenyouwanttobuildsomethingusingPythonspecificallywithobject-orientedprogramming(OOP)WhatImeanbyaldquoprocessrdquoisthatIrsquollgiveyouasetofstepsthatyoudoinorderbutthatyouarenrsquotmeanttobeaslavetoandthatmightnotalwaysworkforeveryproblemTheyarejustagoodstartingpointformanyprogrammingproblemsandshouldnrsquotbeconsideredtheonlywaytosolvethesetypesofproblemsThisprocessisjustonewaytodoitthatyoucanfollowTheprocessisasfollows1Writeordrawabouttheproblem

2Extractkeyconceptsfrom1andresearchthem3Createaclasshierarchyandobjectmapfortheconcepts4Codetheclassesandatesttorunthem5Repeatandrefine

ThewaytolookatthisprocessisthatitisldquotopdownrdquomeaningitstartsfromtheveryabstractlooseideaandthenslowlyrefinesituntiltheideaissolidandsomethingyoucancodeIstartbyjustwritingabouttheproblemandtryingtothinkupanythingIcanaboutitMaybeIrsquollevendrawadiagramortwomaybeamapofsomekindorevenwritemyselfaseriesofemailsdescribingtheproblemThisgivesmeawaytoexpressthekeyconceptsintheproblemandalsoexplorewhatImightalreadyknowaboutitThenIgothroughthesenotesdrawingsanddescriptionsandIpulloutthekeyconceptsTherersquosasimpletricktodoingthisImakealistofallthenounsandverbsinmywritinganddrawingsthenwriteouthowtheyrsquorerelatedThisgivesmeagoodlistofnamesforclassesobjectsandfunctionsinthenextstepItakethislistofconceptsandthenresearchanythatIdonrsquotunderstandsoIcanrefinethemfurtherifneededOnceIhavemylistofconceptsIcreateasimpleoutlinetreeoftheconceptsandhowtheyarerelatedasclassesIcanusuallytakemylistofnounsandstartaskingldquoIsthisonelikeotherconceptnounsThatmeanstheyhaveacommonparentclasssowhatisitcalledrdquoIkeepdoingthisuntilIhaveaclasshierarchythatrsquosjustasimpletreelistoradiagramThenItaketheverbsIhaveandseeifthosearefunctionnamesforeachclassandputtheminmytree

WiththisclasshierarchyfiguredoutIsitdownandwritesomebasicskeletoncodethathasjusttheclassestheirfunctionsandnothingmoreIthenwriteatestthatrunsthiscodeandmakessuretheclassesIrsquovemademakesenseandworkrightSometimesImaywritethetestfirstandothertimesImightwritealittletestalittlecodealittletestandsoonuntilIhavethewholethingbuiltFinallyIkeepcyclingoverthisprocessrepeatingitandrefiningasIgoandmakingitasclearasIcanbeforedoingmoreimplementationIfIgetstuckatanyparticularpartbecauseofaconceptorproblemIhavenrsquotanticipatedthenIsitdownandstarttheprocessoveronjustthatparttofigureitoutmorebeforecontinuingIwillnowgothroughthisprocesswhilecomingupwithagameengineandagameforthisexercise

TheAnalysisofaSimpleGameEngineThegameIwanttomakeiscalledldquoGothonsfromPlanetPercal25rdquoanditwillbeasmallspaceadventuregameWithnothingmorethanthatconceptinmymindIcanexploretheideaandfigureouthowtomakethegamecometolife

WriteorDrawAbouttheProblemIrsquomgoingtowritealittleparagraphforthegameldquoAlienshaveinvadedaspaceshipandourherohastogothroughamazeofroomsdefeatingthemsohecanescapeintoanescapepodtotheplanetbelowThegamewillbemorelikeaZorkorAdventuretypegamewithtextoutputsandfunnywaystodieThegamewillinvolveanenginethatrunsamapfullofroomsorscenesEachroomwillprintitsowndescriptionwhentheplayerentersitandthentelltheenginewhatroomtorunnextoutofthemaprdquoAtthispointIhaveagoodideaforthegameandhowitwouldrunsonowIwanttodescribeeachsceneDeathThisiswhentheplayerdiesandshouldbesomethingfunny

CentralCorridorThisisthestartingpointandhasaGothonalreadystandingtherethattheplayershavetodefeatwithajokebeforecontinuing

LaserWeaponArmoryThisiswheretheherogetsaneutronbombtoblowuptheshipbeforegettingtotheescapepodIthasakeypadtheherohastoguessthenumberfor

TheBridgeThisisanotherbattlescenewithaGothonwheretheheroplacesthebomb

EscapePodThisiswheretheheroescapesbutonlyafterguessingtherightescapepod

AtthispointImightdrawoutamapofthesemaybewritemoredescriptionsofeachroommdashwhatevercomestomindasIexploretheproblem

ExtractKeyConceptsandResearchThemInowhaveenoughinformationtoextractsomeofthenounsandanalyzetheirclasshierarchyFirstImakealistofallthenouns

bullAlienbullPlayerbullShipbullMazebullRoombullScenebullGothonbullEscapePodbullPlanetbullMapbullEnginebullDeathbullCentralCorridorbullLaserWeaponArmorybullTheBridge

IwouldalsopossiblygothroughalltheverbsandseeifanyofthemmightbegoodfunctionnamesbutIrsquollskipthatfornowAtthispointImightalsoresearcheachoftheseconceptsandanythingIdonrsquotknowrightnowForexampleImightplayafewofthesetypesofgamesandmakesureIknowhowtheyworkImightresearchhowshipsaredesignedorhowbombsworkMaybeIrsquollresearchsometechnicalissuelikehowtostorethegamersquosstateinadatabaseAfterIrsquovedonethisresearchImightstartoveratstep1basedonnewinformationIhaveandrewritemydescriptionandextractnewconcepts

CreateaClassHierarchyandObjectMapfortheConceptsOnceIhavethatIturnitintoaclasshierarchybyaskingldquoWhatissimilartootherthingsrdquoIalsoaskldquoWhatisbasicallyjustanotherwordforanotherthingrdquo

RightawayIseethatldquoRoomrdquoandldquoScenerdquoarebasicallythesamethingdependingonhowIwanttodothingsIrsquomgoingtopickldquoScenerdquoforthisgameThenIseethatallthespecificroomslikeldquoCentralCorridorrdquoarebasicallyjustScenesIseealsothatDeathisbasicallyaScenewhichconfirmsmychoiceofldquoScenerdquooverldquoRoomrdquosinceyoucanhaveadeathscenebutadeathroomiskindofoddldquoMazerdquoandldquoMaprdquoarebasicallythesamesoIrsquomgoingtogowithldquoMaprdquosinceIuseditmoreoftenIdonrsquotwanttodoabattlesystemsoIrsquomgoingtoignoreldquoAlienrdquoandldquoPlayerrdquoandsavethatforlaterTheldquoPlanetrdquocouldalsojustbeanothersceneinsteadofsomethingspecificAfterallofthatthoughtprocessIstarttomakeaclasshierarchythatlookslikethisinmytexteditorMapEngineSceneDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodIthengothroughandfigureoutwhatactionsareneededoneachthingbasedonverbsinthedescriptionForexampleIknowfromthedescriptionIrsquomgoingtoneedawaytoldquorunrdquotheengineldquogetthenextscenerdquofromthemapgettheldquoopeningscenerdquoandldquoenterrdquoasceneIrsquolladdthoselikethisMapndashnext_scenendashopening_sceneEnginendashplayScenendashenterDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodNoticehowIjustput-enterunderScenesinceIknowthatallthescenesunderitwillinherititandhavetooverrideitlater

CodetheClassesandaTesttoRunThemOnceIhavethistreeofclassesandsomeofthefunctionsIopenupasourcefileinmyeditorandtrytowritethecodeforitUsuallyIrsquolljustcopy-pastethetreeintothesourcefileandthenedititintoclassesHerersquosasmallexampleofhow

intothesourcefileandthenedititintoclassesHerersquosasmallexampleofhowthismightlookatfirstwithasimplelittletestattheendofthefileClickheretoviewcodeimage

ex43_classespy

1classScene(object)

2

3defenter(self)

4pass

5

6

7classEngine(object)

8

9def__init__(selfscene_map)

10pass

11

12defplay(self)

13pass

14

15classDeath(Scene)

16

17defenter(self)

18pass

19

20classCentralCorridor(Scene)

21

22defenter(self)

23pass

24

25classLaserWeaponArmory(Scene)

26

27defenter(self)

28pass

29

30classTheBridge(Scene)

31

32defenter(self)

33pass

34

35classEscapePod(Scene)

36

37defenter(self)

38pass

39

40

41classMap(object)

42

43def__init__(selfstart_scene)

44pass

45

46defnext_scene(selfscene_name)

47pass

48

49defopening_scene(self)

50pass

51

52

53a_map=Map(central_corridor)

54a_game=Engine(a_map)

55a_gameplay()InthisfileyoucanseethatIsimplyreplicated

thehierarchyIwantedandthenaddedalittlebitofcodeattheend

torunitandseeifitallworksinthisbasicstructureInthe

latersectionsofthisexerciseyoursquollfillintherestofthiscode

andmakeitworktomatchthedescriptionofthegame

RepeatandRefineThelaststepinmylittleprocessisnrsquotsomuchastepasitisawhile-loopYoudonrsquoteverdothisasaone-passoperationInsteadyougobackoverthewholeprocessagainandrefineitbasedoninformationyoursquovelearnedfromlaterstepsSometimesIrsquollgettostep3andrealizethatIneedtoworkon1and2moresoIrsquollstopandgobackandworkonthoseSometimesIrsquollgetaflashofinspirationandjumptotheendtocodeupthesolutioninmyheadwhileIhaveittherebutthenIrsquollgobackanddothepreviousstepstomakesureIcoverallthepossibilitiesIhaveTheotherideainthisprocessisthatitrsquosnotjustsomethingyoudoatonesinglelevelbutsomethingthatyoucandoateverylevelwhenyourunintoaparticularproblemLetrsquossayIdonrsquotknowhowtowritetheEngineplaymethodyetIcanstopanddothiswholeprocessonjustthatonefunctiontofigureouthowtowriteit

TopDownversusBottomUpTheprocessistypicallylabeledldquotopdownrdquosinceitstartsatthemostabstractconcepts(thetop)andworksitswaydowntoactualimplementationIwantyoutousethisprocessIjustdescribedwhenanalyzingproblemsinthebookfromnowonbutyoushouldknowthattherersquosanotherwaytosolveproblemsinprogrammingthatstartswithcodeandgoesldquouprdquototheabstractconceptsThisotherwayislabeledldquobottomuprdquoHerearethegeneralstepsyoufollowtodothis

1Takeasmallpieceoftheproblemhackonsomecodeandgetittorunbarely

barely2Refinethecodeintosomethingmoreformalwithclassesandautomatedtests

3Extractthekeyconceptsyoursquoreusingandresearchthem4Writeadescriptionofwhatrsquosreallygoingon5Gobackandrefinethecodepossiblythrowingitoutandstartingover6Repeatmovingontosomeotherpieceoftheproblem

IfindthisprocessisbetteronceyoursquoremoresolidatprogrammingandarenaturallythinkingincodeaboutproblemsThisprocessisverygoodwhenyouknowsmallpiecesoftheoverallpuzzlebutmaybedonrsquothaveenoughinformationyetabouttheoverallconceptBreakingitdowninlittlepiecesandexploringwithcodethenhelpsyouslowlygrindawayattheproblemuntilyoursquovesolveditHoweverrememberthatyoursolutionwillprobablybemeanderingandweirdsothatrsquoswhymyversionofthisprocessinvolvesgoingbackandfindingresearchthencleaningthingsupbasedonwhatyoursquovelearned

TheCodeforldquoGothonsfromPlanetPercal25rdquoStopIrsquomgoingtoshowyoumyfinalsolutiontotheprecedingproblembutIdonrsquotwantyoutojustjumpinandtypethisupIwantyoutotaketheroughskeletoncodeIdidandtrytomakeitworkbasedonthedescriptionOnceyouhaveyoursolutionthenyoucancomebackandseehowIdiditIrsquomgoingtobreakthisfinalfileex43pydownintosectionsandexplaineachoneratherthandumpallthecodeatonceClickheretoviewcodeimage

ex43py

1fromsysimportexit

2fromrandomimportrandint

3fromtextwrapimportdedentThisisjustourbasicimportsfor

thegameTheonlynewthingistheimportofthededentfunction

fromthetextwrapmoduleThislittlefunctionwillhelpuswriteour

roomdescriptionsusing(triple-quote)stringsItsimplystrips

leadingwhite-spacefromthebeginningsoflinesinastringWithout

thisfunctionusingstylestringsfailsbecausetheyare

indentedonthescreenthesamelevelasinthePythoncode

Clickheretoviewcodeimage

ex43py

1classScene(object)

2

3defenter(self)

4print(Thissceneisnotyetconfigured)

5print(Subclassitandimplemententer())

6exit(1)AsyousawintheskeletoncodeIhaveabase

classforScenethatwillhavethecommonthingsthatallscenesdo

Inthissimpleprogramtheydonrsquotdomuchsothisismorea

demonstrationofwhatyouwoulddotomakeabaseclass

Clickheretoviewcodeimage

ex43py

1classEngine(object)

2

3def__init__(selfscene_map)

4selfscene_map=scene_map

5

6defplay(self)

7current_scene=selfscene_mapopening_scene()

8last_scene=selfscene_mapnext_scene(finished)

9

10whilecurrent_scene=last_scene

11next_scene_name=current_sceneenter()

12current_scene=

selfscene_mapnext_scene(next_scene_name)

13

14besuretoprintoutthelastscene

15current_sceneenter()IalsohavemyEngineclassand

youcanseehowIrsquomalreadyusingthemethodsforMapopening_scene

andMapnext_sceneBecauseIrsquovedoneabitofplanningIcanjust

assumeIrsquollwritethoseandthenusethembeforeIrsquovewrittentheMap

class

Clickheretoviewcodeimage

ex43py

1classDeath(Scene)

2

3quips=[

4YoudiedYoukindasuckatthis

5YourMomwouldbeproudifsheweresmarter

6Suchaluser

7Ihaveasmallpuppythatsbetteratthis

8YoureworsethanyourDadsjokes

9

10]

11

12defenter(self)

13print(Deathquips[randint(0len(selfquips)-1)])

14exit(1)MyfirstsceneistheoddscenenamedDeath

whichshowsyouthesimplestkindofsceneyoucanwrite

Clickheretoviewcodeimage

ex43py

1classCentralCorridor(Scene)

2

3defenter(self)

4print(dedent(

5TheGothonsofPlanetPercal25haveinvadedyour

shipand

6destroyedyourentirecrewYouarethelast

surviving

7memberandyourlastmissionistogettheneutron

destruct

8bombfromtheWeaponsArmoryputitinthebridge

and

9blowtheshipupaftergettingintoanescapepod

10

11Yourerunningdownthecentralcorridortothe

Weapons

12ArmorywhenaGothonjumpsoutredscalyskin

darkgrimy

13teethandevilclowncostumeflowingaroundhis

hate

14filledbodyHesblockingthedoortotheArmory

and

15abouttopullaweapontoblastyou

16))

17

18action=input(gt)

19

20ifaction==shoot

21print(dedent(

22Quickonthedrawyouyankoutyourblaster

andfire

23itattheGothonHisclowncostumeis

flowingand

24movingaroundhisbodywhichthrowsoffyour

aim

25Yourlaserhitshiscostumebutmisseshim

entirely

26Thiscompletelyruinshisbrandnewcostume

hismother

27boughthimwhichmakeshimflyintoan

insanerage

28andblastyourepeatedlyinthefaceuntil

youare

29deadThenheeatsyou

30))

31returndeath

32

33elifaction==dodge

34print(dedent(

35Likeaworldclassboxeryoudodgeweave

slipand

36sliderightastheGothonsblastercranksa

laser

37pastyourheadInthemiddleofyourartful

dodge

38yourfootslipsandyoubangyourheadonthe

metal

39wallandpassoutYouwakeupshortlyafter

onlyto

40dieastheGothonstompsonyourheadand

eatsyou

41))

42returndeath

43

44elifaction==tellajoke

45print(dedent(

46LuckyforyoutheymadeyoulearnGothon

insultsin

47theacademyYoutelltheoneGothonjoke

youknow

48Lbhezbgurevffbsngjurafurfvgfnebhaq

gurubhfr

49furfvgfnebhaqgurubhfrTheGothonstops

tries

50nottolaughthenbustsoutlaughingand

cantmove

51Whileheslaughingyourunupandshoothim

squarein

52theheadputtinghimdownthenjumpthrough

the

53WeaponArmorydoor

54))

55returnlaser_weapon_armory

56

57else

58print(DOESNOTCOMPUTE)

59returncentral_corridor

AfterthatIrsquovecreatedtheCentralCorridorwhichisthestartofthegameIrsquomdoingthescenesforthegamebeforetheMapbecauseIneedtoreferencethemlaterYoushouldalsoseehowIusethededentfunctiononline4TryremovingitlatertoseewhatitdoesClickheretoviewcodeimage

ex43py

1classLaserWeaponArmory(Scene)

2

3defenter(self)

4print(dedent(

5YoudoadiverollintotheWeaponArmory

crouchandscan

6theroomformoreGothonsthatmightbe

hidingItsdead

7quiettooquietYoustandupandruntothe

farsideof

8theroomandfindtheneutronbombinits

container

9Theresakeypadlockontheboxandyouneed

thecodeto

10getthebomboutIfyougetthecodewrong10

timesthen

11thelockclosesforeverandyoucantgetthe

bombThe

12codeis3digits

13))

14

15code=frandint(19)randint(19)randint(19)

16guess=input([keypad]gt)

17guesses=0

18

19whileguess=codeandguesseslt10

20print(BZZZZEDDD)

21guesses+=1

22guess=input([keypad]gt)

23

24ifguess==code

25print(dedent(

26Thecontainerclicksopenandtheseal

breaksletting

27gasoutYougrabtheneutronbombandrun

asfastas

28youcantothebridgewhereyoumustplace

itinthe

29rightspot

30))

31returnthe_bridge

32else

33print(dedent(

34Thelockbuzzesonelasttimeandthenyou

heara

35sickeningmeltingsoundasthemechanismis

fused

36togetherYoudecidetositthereand

finallythe

37Gothonsblowuptheshipfromtheirshipand

youdie

38))

39returndeath

40

41

42

43classTheBridge(Scene)

44

45defenter(self)

46print(dedent(

47YouburstontotheBridgewiththenetron

destructbomb

48underyourarmandsurprise5Gothonswhoare

tryingto

49takecontroloftheshipEachofthemhasan

evenuglier

50clowncostumethanthelastTheyhavent

pulledtheir

51weaponsoutyetastheyseetheactivebomb

underyour

52armanddontwanttosetitoff

53))

54

55action=input(gt)

56

57ifaction==throwthebomb

58print(dedent(

59Inapanicyouthrowthebombatthegroup

ofGothons

60andmakealeapforthedoorRightasyou

dropita

61Gothonshootsyourightinthebackkilling

youAs

62youdieyouseeanotherGothonfrantically

tryto

63disarmthebombYoudieknowingtheywill

probably

64blowupwhenitgoesoff

65))

66returndeath

67

68elifaction==slowlyplacethebomb

69print(dedent(

70Youpointyourblasteratthebombunder

yourarmand

71theGothonsputtheirhandsupandstartto

sweat

72Youinchbackwardtothedooropenitand

then

73carefullyplacethebombonthefloor

pointingyour

74blasteratitYouthenjumpbackthrough

thedoor

75punchtheclosebuttonandblastthelockso

the

76GothonscantgetoutNowthatthebombis

placed

77youruntotheescapepodtogetoffthis

tincan

78))

79

80returnescape_pod

81else

82print(DOESNOTCOMPUTE)

83returnthe_bridge

84

85

86classEscapePod(Scene)

87

88defenter(self)

89print(dedent(

90Yourushthroughtheshipdesperatelytryingto

makeitto

91theescapepodbeforethewholeship

explodesItseems

92likehardlyanyGothonsareontheshipsoyour

runis

93clearofinterferenceYougettothechamber

withthe

94escapepodsandnowneedtopickoneto

takeSomeof

95themcouldbedamagedbutyoudonthavetimeto

look

96Theres5podswhichonedoyoutake

97))

98

99good_pod=randint(15)

100guess=input([pod]gt)

101

102

103ifint(guess)=good_pod

104print(dedent(

105Youjumpintopodguessandhittheeject

button

106Thepodescapesoutintothevoidofspace

then

107implodesasthehullrupturescrushingyour

bodyinto

108jamjelly

109))

110returndeath

111else

112print(dedent(

113Youjumpintopodguessandhittheeject

button

114Thepodeasilyslidesoutintospaceheading

tothe

115planetbelowAsitfliestotheplanet

youlook

116backandseeyourshipimplodethenexplode

likea

117brightstartakingouttheGothonshipat

thesame

118timeYouwon

119))

120

121returnfinished

122

123classFinished(Scene)

124

125defenter(self)

126print(YouwonGoodjob)

127returnfinished

ThisistherestofthegamersquosscenesandsinceIknowIneedthemandhavethoughtabouthowtheyrsquollflowtogetherIrsquomabletocodethemupdirectlyIncidentallyIwouldnrsquotjusttypeallthiscodeinRememberIsaidtotryandbuildthisincrementallyonelittlebitatatimeIrsquomjustshowingyouthefinalresultClickheretoviewcodeimage

ex43py

1classMap(object)

2

3scenes=

4central_corridorCentralCorridor()

5laser_weapon_armoryLaserWeaponArmory()

6the_bridgeTheBridge()

7escape_podEscapePod()

8deathDeath()

9finishedFinished()

10

11

12def__init__(selfstart_scene)

13selfstart_scene=start_scene

14

15defnext_scene(selfscene_name)

16val=Mapscenesget(scene_name)

17returnval

18

19defopening_scene(self)

20returnselfnext_scene(selfstart_scene)AfterthatI

havemyMapclassandyoucanseeitisstoringeachscenebyname

inadictionaryandthenIrefertothatdictwithMapscenesThis

isalsowhythemapcomesafterthescenesbecausethedictionaryhas

torefertothescenessotheyhavetoexist

Clickheretoviewcodeimage

ex43py

1a_map=Map(central_corridor)

2a_game=Engine(a_map)

3a_gameplay()FinallyIrsquovegotmycodethatrunsthegameby

makingaMapthenhandingthatmaptoanEnginebeforecallingplay

tomakethegamework

WhatYouShouldSeeMakesureyouunderstandthegameandthatyoutriedtosolveityourselffirstOnethingtodoifyoursquorestumpedischeatalittlebyreadingmycodethencontinuetryingtosolveityourselfWhenIrunmygameitlookslikethisClickheretoviewcodeimage

Exercise43Session

$python36ex43py

TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyedyourentirecrewYouarethelastsurviving

memberandyourlastmissionistogettheneutrondestruct

bombfromtheWeaponsArmoryputitinthebridgeand

blowtheshipupaftergettingintoanescapepod

YourerunningdownthecentralcorridortotheWeapons

ArmorywhenaGothonjumpsoutredscalyskindarkgrimy

teethandevilclowncostumeflowingaroundhishate

filledbodyHesblockingthedoortotheArmoryand

abouttopullaweapontoblastyou

gtdodge

Likeaworldclassboxeryoudodgeweaveslipand

sliderightastheGothonsblastercranksalaser

pastyourheadInthemiddleofyourartfuldodge

yourfootslipsandyoubangyourheadonthemetal

wallandpassoutYouwakeupshortlyafteronlyto

dieastheGothonstompsonyourheadandeatsyou

YoureworsethanyourDadsjokes

StudyDrills1ChangeitMaybeyouhatethisgameItcouldbetooviolentormaybeyouarenrsquotintosci-fiGetthegameworkingthenchangeittowhatyoulikeThisisyourcomputeryoumakeitdowhatyouwant

2IhaveabuginthiscodeWhyisthedoorlockguessing11times3Explainhowreturningthenextroomworks4AddcheatcodestothegamesoyoucangetpastthemoredifficultroomsIcandothiswithtwowordsononeline

5GobacktomydescriptionandanalysisthentrytobuildasmallcombatsystemfortheheroandthevariousGothonsheencounters

6ThisisactuallyasmallversionofsomethingcalledaldquofinitestatemachinerdquoReadaboutthemTheymightnotmakesensebuttryanyway

CommonStudentQuestionsWherecanIfindstoriesformyowngamesYoucanmakethemupjustlikeyouwouldtellastorytoafriendOryoucantakesimplescenesfromabookormovieyoulike

Exercise44InheritanceversusComposition

InthefairytalesaboutheroesdefeatingevilvillainstherersquosalwaysadarkforestofsomekindItcouldbeacaveaforestanotherplanetjustsomeplacethateveryoneknowstheheroshouldnrsquotgoOfcourseshortlyafterthevillainisintroducedyoufindoutyestheherohastogotothatstupidforesttokillthebadguyItseemstheherojustkeepsgettingintosituationsthatrequirehimtoriskhislifeinthisevilforestYourarelyreadfairytalesabouttheheroeswhoaresmartenoughtojustavoidthewholesituationentirelyYouneverhearaherosayldquoWaitaminuteifIleavetomakemyfortunesonthehighseasleavingButtercupbehindIcoulddieandthenshersquodhavetomarrysomeuglyprincenamedHumperdinkHumperdinkIthinkIrsquollstayhereandstartaFarmBoyforRentbusinessrdquoIfhedidthattherersquodbenofireswampdyingreanimationswordfightsgiantsoranykindofstoryreallyBecauseofthistheforestinthesestoriesseemstoexistlikeablackholethatdragstheheroinnomatterwhattheydoInobject-orientedprogramminginheritanceistheevilforestExperiencedprogrammersknowtoavoidthisevilbecausetheyknowthatdeepinsidetheDarkForestInheritanceistheEvilQueenMultipleInheritanceShelikestoeatsoftwareandprogrammerswithhermassivecomplexityteethchewingonthefleshofthefallenButtheforestissopowerfulandsotemptingthatnearlyeveryprogrammerhastogointoitandtrytomakeitoutalivewiththeEvilQueenrsquosheadbeforetheycancallthemselvesrealprogrammersYoujustcanrsquotresisttheInheritanceForestrsquospullsoyougoinAftertheadventureyoulearntojuststayoutofthatstupidforestandbringanarmyifyouareeverforcedtogoinagainThisisbasicallyafunnywaytosaythatIrsquomgoingtoteachyousomethingyoushouldusecarefullycalledinheritanceProgrammerswhoarecurrentlyintheforestbattlingtheQueenwillprobablytellyouthatyouhavetogoinTheysaythisbecausetheyneedyourhelpsincewhattheyrsquovecreatedisprobablytoomuchforthemtohandleButyoushouldalwaysrememberthisMostoftheusesofinheritancecanbesimplifiedorreplacedwithcompositionandmultipleinheritanceshouldbeavoidedatallcosts

WhatIsInheritanceInheritanceisusedtoindicatethatoneclasswillgetmostorallofitsfeaturesfromaparentclassThishappensimplicitlywheneveryouwriteclass

Foo(Bar)whichsaysldquoMakeaclassFoothatinheritsfromBarrdquoWhenyoudothisthelanguagemakesanyactionthatyoudooninstancesofFooalsoworkasiftheyweredonetoaninstanceofBarDoingthisletsyouputcommonfunctionalityintheBarclassthenspecializethatfunctionalityintheFooclassasneededWhenyouaredoingthiskindofspecializationtherearethreewaysthattheparentandchildclassescaninteract1Actionsonthechildimplyanactionontheparent

2Actionsonthechildoverridetheactionontheparent3Actionsonthechildaltertheactionontheparent

Iwillnowdemonstrateeachoftheseinorderandshowyoucodeforthem

ImplicitInheritanceFirstIwillshowyoutheimplicitactionsthathappenwhenyoudefineafunctionintheparentbutnotinthechildClickheretoviewcodeimage

ex44apy

1classParent(object)

2

3defimplicit(self)

4print(PARENTimplicit())

5

6classChild(Parent)

7pass

8

9dad=Parent()

10son=Child()

11

12dadimplicit()

13sonimplicit()TheuseofpassundertheclassChildishow

youtellPythonthatyouwantanemptyblockThiscreatesaclass

namedChildbutsaysthattherersquosnothingnewtodefineinit

InsteaditwillinheritallofitsbehaviorfromParentWhenyourun

thiscodeyougetthefollowingExercise44aSession

$python36ex44apy

PARENTimplicit()

PARENTimplicit()NoticehoweventhoughIrsquomcallingsonimplicit()

online13andeventhoughChilddoesnothaveanimplicitfunction

defineditstillworksanditcallstheonedefinedinParentThis

showsyouthatifyouputfunctionsinabaseclass(ieParent)

thenallsubclasses(ieChild)willautomaticallygetthose

featuresVeryhandyforrepetitivecodeyouneedinmanyclasses

OverrideExplicitlyTheproblemwithhavingfunctionscalledimplicitlyissometimesyouwantthechildtobehavedifferentlyInthiscaseyouwanttooverridethefunctioninthechildeffectivelyreplacingthefunctionalityTodothisjustdefineafunctionwiththesamenameinChildHerersquosanexampleClickheretoviewcodeimage

ex44bpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6classChild(Parent)

7

8defoverride(self)

9print(CHILDoverride())

10

11dad=Parent()

12son=Child()

13

14dadoverride()

15sonoverride()InthisexampleIhaveafunctionnamedoverride

inbothclassessoletrsquosseewhathappenswhenIrunit

Exercise44bSession

$python36ex44bpy

PARENToverride()

CHILDoverride()Asyoucanseewhenline14runsitrunsthe

Parentoverridefunctionbecausethatvariable(dad)isaParentBut

whenline15runsitprintsouttheChildoverridemessagesbecause

sonisaninstanceofChildandChildoverridesthatfunctionby

definingitsownversion

Takeabreakrightnowandtryplayingwiththesetwoconceptsbeforecontinuing

AlterBeforeorAfter

AlterBeforeorAfterThethirdwaytouseinheritanceisaspecialcaseofoverridingwhereyouwanttoalterthebehaviorbeforeoraftertheParentclassrsquosversionrunsYoufirstoverridethefunctionjustlikeinthelastexamplebutthenyouuseaPythonbuilt-infunctionnamedsupertogettheParentversiontocallHerersquostheexampleofdoingthatsoyoucanmakesenseofthisdescriptionClickheretoviewcodeimage

ex44cpy

1classParent(object)

2

3defaltered(self)

4print(PARENTaltered())

5

6classChild(Parent)

7

8defaltered(self)

9print(CHILDBEFOREPARENTaltered())

10super(Childself)altered()

11print(CHILDAFTERPARENTaltered())

12

13dad=Parent()

14son=Child()

15

16dadaltered()

17sonaltered()Theimportantlineshereare9ndash11whereinthe

ChildIdothefollowingwhensonaltered()iscalled1Because

IrsquoveoverriddenParentalteredtheChildalteredversionrunsand

line9executeslikeyoursquodexpect

2InthiscaseIwanttodoabeforeandaftersoafterline9IwanttousesupertogettheParentalteredversion

3Online10Icallsuper(Childself)altered()whichisawareofinheritanceandwillgettheParentclassforyouYoushouldbeabletoreadthisasldquocallsuperwithargumentsChildandselfthencallthefunctionalteredonwhateveritreturnsrdquo

4AtthispointtheParentalteredversionofthefunctionrunsandthatprintsouttheParentmessage

5FinallythisreturnsfromtheParentalteredandtheChildalteredfunctioncontinuestoprintouttheaftermessage

IfyourunthisyoushouldseethisClickheretoviewcodeimage

Exercise44cSession

$python36ex44cpy

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

AllThreeCombinedTodemonstratealloftheseIhaveafinalversionthatshowseachkindofinteractionfrominheritanceinonefileClickheretoviewcodeimage

ex44dpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6defimplicit(self)

7print(PARENTimplicit())

8

9defaltered(self)

10print(PARENTaltered())

11

12classChild(Parent)

13

14defoverride(self)

15print(CHILDoverride())

16

17defaltered(self)

18print(CHILDBEFOREPARENTaltered())

19super(Childself)altered()

20print(CHILDAFTERPARENTaltered())

21

22dad=Parent()

23son=Child()

24

25dadimplicit()

26sonimplicit()

27

28dadoverride()

29sonoverride()

30

31dadaltered()

32sonaltered()Gothrougheachlineofthiscodeandwritea

commentexplainingwhatthatlinedoesandwhetheritrsquosanoverride

ornotThenrunitandconfirmyougetwhatyouexpectedClickhere

toviewcodeimage

Exercise44dSession

$python36ex44dpy

PARENTimplicit()

PARENTimplicit()

PARENToverride()

CHILDoverride()

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

TheReasonforsuper()ThisshouldseemlikecommonsensebutthenwegetintotroublewithathingcalledmultipleinheritanceMultipleinheritanceiswhenyoudefineaclassthatinheritsfromoneormoreclasseslikethisClickheretoviewcodeimage

classSuperFun(ChildBadStuff)

passThisislikesayingldquoMakeaclassnamedSuperFunthat

inheritsfromtheclassesChildandBadStuffatthesametimerdquo

InthiscasewheneveryouhaveimplicitactionsonanySuperFuninstancePythonhastolookupthepossiblefunctionintheclasshierarchyforbothChildandBadStuffbutitneedstodothisinaconsistentorderTodothisPythonusesldquomethodresolutionorderrdquo(MRO)andanalgorithmcalledC3togetitstraightBecausetheMROiscomplexandawell-definedalgorithmisusedPythoncanrsquotleaveittoyoutogettheMROrightInsteadPythongivesyouthesuper()functionwhichhandlesallofthisforyouintheplacesthatyouneedthealteringtypeofactionsasIdidinChildalteredWithsuper()youdonrsquothavetoworryaboutgettingthisrightandPythonwillfindtherightfunctionforyou

Usingsuper()with__init__Themostcommonuseofsuper()isactuallyin__init__functionsinbaseclassesThisisusuallytheonlyplacewhereyouneedtodosomethingsina

childthencompletetheinitializationintheparentHerersquosaquickexampleofdoingthatintheChildClickheretoviewcodeimage

classChild(Parent)

def__init__(selfstuff)

selfstuff=stuff

super(Childself)__init__()Thisisprettymuchthesameas

theChildalteredexampleaboveexceptIrsquomsettingsomevariablesin

the__init__beforehavingtheParentinitializewithits

Parent__init__

CompositionInheritanceisusefulbutanotherwaytodotheexactsamethingisjusttouseotherclassesandmodulesratherthanrelyonimplicitinheritanceIfyoulookatthethreewaystoexploitinheritancetwoofthethreeinvolvewritingnewcodetoreplaceoralterfunctionalityThiscaneasilybereplicatedbyjustcallingfunctionsinamoduleHerersquosanexampleofdoingthisClickheretoviewcodeimage

ex44epy

1classOther(object)

2

3defoverride(self)

4print(OTHERoverride())

5

6defimplicit(self)

7print(OTHERimplicit())

8

9defaltered(self)

10print(OTHERaltered())

11

12classChild(object)

13

14def__init__(self)

15selfother=Other()

16

17defimplicit(self)

18selfotherimplicit()

19

20defoverride(self)

21print(CHILDoverride())

22

23defaltered(self)

24print(CHILDBEFOREOTHERaltered())

25selfotheraltered()

26print(CHILDAFTEROTHERaltered())

27

28son=Child()

29

30sonimplicit()

31sonoverride()

32sonaltered()InthiscodeIrsquomnotusingthenameParentsince

thereisnotaparent-childis-arelationshipThisisahas-a

relationshipwhereChildhas-aOtherthatitusestogetitswork

doneWhenIrunthisIgetthefollowingoutputExercise44e

Session

$python36ex44epy

OTHERimplicit()

CHILDoverride()

CHILDBEFOREOTHERaltered()

OTHERaltered()

CHILDAFTEROTHERaltered()Youcanseethatmostofthecodein

ChildandOtheristhesametoaccomplishthesamethingTheonly

differenceisthatIhadtodefineaChildimplicitfunctiontodo

thatoneactionIcouldthenaskmyselfifIneedthisOthertobea

classandcouldIjustmakeitintoamodulenamedotherpy

WhentoUseInheritanceorCompositionThequestionofldquoinheritanceversuscompositionrdquocomesdowntoanattempttosolvetheproblemofreusablecodeYoudonrsquotwanttohaveduplicatedcodealloveryoursoftwaresincethatrsquosnotcleanandefficientInheritancesolvesthisproblembycreatingamechanismforyoutohaveimpliedfeaturesinbaseclassesCompositionsolvesthisbygivingyoumodulesandthecapabilitytocallfunctionsinotherclassesIfbothsolutionssolvetheproblemofreusethenwhichoneisappropriateinwhichsituationsTheanswerisincrediblysubjectivebutIrsquollgiveyoumythreeguidelinesforwhentodowhich1AvoidmultipleinheritanceatallcostsasitrsquostoocomplextobereliableIfyoursquorestuckwithitthenbepreparedtoknowtheclasshierarchyandspendtimefindingwhereeverythingiscomingfrom

2Usecompositiontopackagecodeintomodulesthatareusedinmanydifferentunrelatedplacesandsituations

3Useinheritanceonlywhenthereareclearlyrelatedreusablepiecesofcodethatfitunderasinglecommonconceptorifyouhavetobecauseofsomethingyoursquoreusing

DonotbeaslavetotheserulesThethingtorememberaboutobject-orientedprogrammingisthatitisentirelyasocialconventionprogrammershavecreatedtopackageandsharecodeBecauseitrsquosasocialconventionbutonethatrsquoscodifiedinPythonyoumaybeforcedtoavoidtheserulesbecauseofthepeopleyouworkwithInthatcasefindouthowtheyusethingsandthenjustadapttothesituation

StudyDrillsThereisonlyoneStudyDrillforthisexercisebecauseitisabigexerciseGoandreadhttpwwwpythonorgdevpepspep-0008andstarttryingtouseitinyourcodeYoursquollnoticethatsomeofitisdifferentfromwhatyoursquovebeenlearninginthisbookbutnowyoushouldbeabletounderstandtheirrecommendationsandusetheminyourowncodeTherestofthecodeinthisbookmayormaynotfollowtheseguidelinesdependingonwhetheritmakesthecodemoreconfusingIsuggestyoualsodothisascomprehensionismoreimportantthanimpressingeveryonewithyourknowledgeofesotericstylerules

CommonStudentQuestionsHowdoIgetbetteratsolvingproblemsthatIhavenrsquotseenbeforeTheonlywaytogetbetteratsolvingproblemsistosolveasmanyproblemsasyoucanbyyourselfTypicallypeoplehitadifficultproblemandthenrushouttofindananswerThisisfinewhenyouhavetogetthingsdonebutifyouhavethetimetosolveityourselfthentakethattimeStopandbangyourheadagainsttheproblemforaslongaspossibletryingeverypossiblethinguntilyousolveitorgiveupAfterthattheanswersyoufindwillbemoresatisfyingandyoursquolleventuallygetbetteratsolvingproblems

ArenrsquotobjectsjustcopiesofclassesInsomelanguages(likeJavaScript)thatistrueThesearecalledprototypelanguagesandtherearenotmanydifferencesbetweenobjectsandclassesotherthanusageInPythonhoweverclassesactastemplatesthatldquomintrdquonewobjectssimilartohowcoinsaremintedusingadie(template)

Exercise45YouMakeaGame

YouneedtostartlearningtofeedyourselfHopefullyasyouhaveworkedthroughthisbookyouhavelearnedthatalltheinformationyouneedisontheinternetYoujusthavetogosearchforitTheonlythingyouhavebeenmissingaretherightwordsandwhattolookforwhenyousearchNowyoushouldhaveasenseofitsoitrsquosabouttimeyoustruggledthroughabigprojectandtriedtogetitworkingHereareyourrequirements

1MakeadifferentgamefromtheoneImade2UsemorethanonefileanduseimporttousethemMakesureyouknowwhatthatis

3Useoneclassperroomandgivetheclassesnamesthatfittheirpurposes(likeGoldRoomKoiPondRoom)

4YourrunnerwillneedtoknowabouttheseroomssomakeaclassthatrunsthemandknowsaboutthemTherersquoreplentyofwaystodothisbutconsiderhavingeachroomreturnwhatroomisnextorsettingavariableofwhatroomisnext

OtherthanthatIleaveittoyouSpendawholeweekonthisandmakeitthebestgameyoucanUseclassesfunctionsdictslistsanythingyoucantomakeitniceThepurposeofthislessonistoteachyouhowtostructureclassesthatneedotherclassesinsideotherfilesRememberIrsquomnottellingyouexactlyhowtodothisbecauseyouhavetodothisyourselfGofigureitoutProgrammingisproblemsolvingandthatmeanstryingthingsexperimentingfailingscrappingyourworkandtryingagainWhenyougetstuckaskforhelpandshowpeopleyourcodeIftheyaremeantoyouignorethemandfocusonthepeoplewhoarenotmeanandoffertohelpKeepworkingitandcleaningituntilitrsquosgoodthenshowitsomemoreGoodluckandseeyouinaweekwithyourgame

EvaluatingYourGameInthisexerciseyouwillevaluatethegameyoujustmadeMaybeyougotpartwaythroughitandyougotstuckMaybeyougotitworkingbutjustbarelyEitherwaywersquoregoingtogothroughabunchofthingsyoushouldknownowandmakesureyoucoveredtheminyourgameWersquoregoingtostudyproperlyformattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquo

formattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquoknowledgeWhywouldIhaveyoutrytodoityourselfandthenshowyouhowtodoitrightFromnowoninthebookIrsquomgoingtotrytomakeyouself-sufficientIrsquovebeenholdingyourhandmostlythiswholetimeandIcanrsquotdothatformuchlongerIrsquomnowinsteadgoingtogiveyouthingstodohaveyoudothemonyourownandthengiveyouwaystoimprovewhatyoudidYouwillstruggleatfirstandprobablybeveryfrustratedbutstickwithitandeventuallyyouwillbuildamindforsolvingproblemsYouwillstarttofindcreativesolutionstoproblemsratherthanjustcopysolutionsoutoftextbooks

FunctionStyleAlltheotherrulesIrsquovetaughtyouabouthowtomakeanicefunctionapplyherebutaddthesethings

bullForvariousreasonsprogrammerscallfunctionsthatarepartofclassesldquomethodsrdquoItrsquosmostlymarketingbutjustbewarnedthateverytimeyousayldquofunctionrdquotheyrsquollannoyinglycorrectyouandsayldquomethodrdquoIftheygettooannoyingjustaskthemtodemonstratethemathematicalbasisthatdetermineshowaldquomethodrdquoisdifferentfromaldquofunctionrdquoandtheyrsquollshutup

bullWhenyouworkwithclassesmuchofyourtimeisspenttalkingaboutmakingtheclassldquodothingsrdquoInsteadofnamingafunctionafterwhatthefunctiondoesinsteadnameitasifitrsquosacommandyouaregivingtotheclassForexamplepopissayingldquoHeylistpopthisoffrdquoItisnrsquotcalledremove_from_end_of_listbecauseeventhoughthatrsquoswhatitdoesthatrsquosnotacommandtoalist

bullKeepyourfunctionssmallandsimpleForsomereasonwhenpeoplestartlearningaboutclassestheyforgetthis

ClassStylebullYourclassshoulduseldquocamelcaserdquoasinSuperGoldFactoryratherthanldquounderscoreformatrdquoasinsuper_gold_factory

bullTrynottodotoomuchinyour__init__functionsItmakesthemhardertouse

bullYourotherfunctionsshoulduseunderscoreformatsowritemy_awesome_hairandnotmyawesomehairorMyAwesomeHair

bullBeconsistentinhowyouorganizeyourfunctionargumentsIfyourclass

hastodealwithusersdogsandcatskeepthatorderthroughoutunlessitreallydoesnrsquotmakesenseIfyouhaveonefunctionthattakes(dogcatuser)andtheothertakes(usercatdog)itrsquollbehardtouse

bullTrynottousevariablesthatcomefromthemoduleorglobalsTheyshouldbefairlyself-contained

bullAfoolishconsistencyisthehobgoblinoflittlemindsConsistencyisgoodbutfoolishlyfollowingsomeidioticmantrabecauseeveryoneelsedoesisbadstyleThinkforyourself

bullAlwaysalwayshaveclassName(object)formatorelseyouwillbeinbigtrouble

CodeStylebullGiveyourcodeverticalspacesopeoplecanreaditYouwillfindsomeverybadprogrammerswhoareabletowritereasonablecodebutwhodonotaddanyspacesThisisbadstyleinanylanguagebecausethehumaneyeandbrainusespaceandverticalalignmenttoscanandseparatevisualelementsNothavingspaceisthesameasgivingyourcodeanawesomecamouflagepaintjob

bullIfyoucanrsquotreaditoutlouditrsquosprobablyhardtoreadIfyouarehavingaproblemmakingsomethingeasytousetryreadingitoutloudNotonlydoesthisforceyoutoslowdownandreallyreaditbutitalsohelpsyoufinddifficultpassagesandthingstochangeforreadability

bullTrytodowhatotherpeoplearedoinginPythonuntilyoufindyourownstyle

bullOnceyoufindyourownstyledonotbeajerkaboutitWorkingwithotherpeoplersquoscodeispartofbeingaprogrammerandotherpeoplehavereallybadtasteTrustmeyouwillprobablyhavereallybadtastetooandnotevenrealizeit

bullIfyoufindsomeonewhowritescodeinastyleyouliketrywritingsomethingthatmimicsthatstyle

GoodCommentsbullProgrammerswilltellyouthatyourcodeshouldbereadableenoughthatyoudonotneedcommentsTheyrsquollthentellyouintheirmostofficialsoundingvoiceldquoErgooneshouldneverwritecommentsordocumentationQEDrdquoThoseprogrammersareeitherconsultantswhogetpaidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendto

paidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendtoneverworkwithotherpeopleIgnorethemandwritecomments

bullWhenyouwritecommentsdescribewhyyouaredoingwhatyouaredoingThecodealreadysayshowsowhyyoudidthingsthewayyoudidismoreimportant

bullWhenyouwritedoccommentsforyourfunctionsmakethecommentsdocumentationforsomeonewhowillhavetouseyourcodeYoudonothavetogocrazybutanicelittlesentenceaboutwhatsomeonecandowiththatfunctionhelpsalot

bullWhilecommentsaregoodtoomanyarebadandyouhavetomaintainthemKeepyourcommentsrelativelyshortandtothepointandifyouchangeafunctionreviewthecommenttomakesureitrsquosstillcorrect

EvaluateYourGameIwantyoutonowpretendyouaremeAdoptaverysternlookprintoutyourcodeandtakearedpenandmarkeverymistakeyoufindincludinganythingfromthisexerciseandfromotherguidelinesyoursquovereadsofarOnceyouaredonemarkingyourcodeupIwantyoutofixeverythingyoucameupwithThenrepeatthisacoupleoftimeslookingforanythingthatcouldbebetterUseallthetricksIrsquovegivenyoutobreakyourcodedownintothesmallesttiniestlittleanalysisyoucanThepurposeofthisexerciseistotrainyourattentiontodetailonclassesOnceyouaredonewiththisbitofcodefindsomeoneelsersquoscodeanddothesamethingGothroughaprintedcopyofsomepartofitandpointoutallthemistakesandstyleerrorsyoufindThenfixitandseeifyourfixescanbedonewithoutbreakingthatprogramIwantyoutodonothingbutevaluateandfixcodefortheweekmdashyourowncodeandotherpeoplersquosItrsquollbeprettyhardworkbutwhenyouaredoneyourbrainwillbewiredtightlikeaboxerrsquoshands

Exercise46AProjectSkeleton

ThiswillbewhereyoustartlearninghowtosetupagoodprojectldquoskeletonrdquodirectoryThisskeletondirectorywillhaveallthebasicsyouneedtogetanewprojectupandrunningItwillhaveyourprojectlayoutautomatedtestsmodulesandinstallscriptsWhenyougotomakeanewprojectjustcopythisdirectorytoanewnameandeditthefilestogetstarted

macOSLinuxSetupBeforeyoucanbeginthisexerciseyouneedtoinstallsomesoftwareforPythonbyusingatoolcalledpip36(orjustpip)toinstallnewmodulesThepip36commandshouldbeincludedwithyourpython36installationYoursquollwanttoverifythisusingthiscommand

$pip36list

pip(901)

setuptools(2880)

$

YoucanignoreanydeprecationwarningifyouseeitYoumayalsoseeothertoolsinstalledbutthebaseshouldbepipandsetuptoolsOnceyoursquoveverifiedthisyoucantheninstallvirtualenvClickheretoviewcodeimage

$sudopip36installvirtualenv

Password

Collectingvirtualenv

Downloadingvirtualenvndash1510ndashpy2py3ndashnonendashanywhl(18MB)

100|||||||||||||||||||||||||||||||||18MB11MBs

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

$

ThisisforLinuxormacOSsystemsIfyoursquoreonLinuxmacOSyoursquollwanttorunthefollowingcommandtomakesureyouusethecorrectvirtualenvClickheretoviewcodeimage

$whereisvirtualenv

LibraryFrameworksPythonframeworkVersions36binvirtualenv

YoushouldseesomethingliketheaboveonmacOSbutLinuxwillbevariableOnLinuxyoumighthaveanactualvirtualenv36commandoryoumay

bebetteroffinstallingapackageforitfromyourpackagemanagementsystemOnceyoursquoveinstalledvirtualenvyoucanuseittocreatealdquofakerdquoPythoninstallationwhichmakesiteasiertomanageversionsofyourpackagesfordifferentprojectsFirstrunthiscommandandIrsquollexplainwhatitrsquosdoingClickheretoviewcodeimage

$mkdir~venvs

$virtualenvndashndashsystemndashsitendashpackages~venvslpthw

$~venvslpthwbinactivate

(lpthw)$

Herersquoswhatrsquosgoingonlinebyline1YoucreateadirectorycalledvenvsinyourHOME~tostoreallyourvirtualenvironments

2Yourunvirtualenvandtellittoincludethesystemsitepackages(--system-site-packages)theninstructittobuildthevirtualenvin~venvslpthw

3Youthenldquosourcerdquothelpthwvirtualenvironmentbyusingtheoperatorinbashfollowedbythe~venvslpthwbinactivatescript

4Finallyyourpromptchangestoinclude(lpthw)soyouknowthatyoursquoreusingthatvirtualenvironment

NowyoucanseewherethingsareinstalledClickheretoviewcodeimage

(lpthw)$whichpython

Userszedshawvenvslpthwbinpython

(lpthw)$python

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

(lpthw)$

YoucanseethatthepythonthatgetsrunisinstalledintheUserszedshawvenvslpthwbinpythondirectoryinsteadoftheoriginallocationThisalsosolvestheproblemofhavingtotypepython36sinceitinstallsbothClickheretoviewcodeimage

$whichpython36

Userszedshawvenvslpthwbinpython36

(lpthw)$

YoursquollfindthesamethingforvirtualenvandpipcommandsThefinalstepinthissetupistoinstallnoseatestingframeworkwersquolluseinthisexerciseClickheretoviewcodeimage

$pipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB32MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)$

Windows10SetupTheWindows10installisalittlesimplerthanonLinuxormacOSbutonlyifyouhaveoneversionofPythoninstalledIfyouhavebothPython36andPython27installedthenyouareonyourownasitismuchtoodifficulttomanagemultipleinstallationsIfyouhavefollowedthebooksofarandhaveonlyPython36thenherersquoswhatyoudoFirstchangetoyourhomedirectoryandconfirmyoursquorerunningtherightversionofpythonClickheretoviewcodeimage

gtcd~

gtpython

Python360(v36041df79263a11Dec232016080612)

[MSCv190064bit(AMD64)]onwin32

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

Thenyoursquollwanttorunpiptoconfirmyouhaveabasicinstall

gtpiplist

pip(901)

setuptools(2880)

YoucansafelyignoreanydeprecationwarninganditrsquosalrightifyouhaveotherpackagesinstalledNextyoursquollinstallvirtualenvforsettingupsimplevirtualenvironmentsfortherestofthebookClickheretoviewcodeimage

gtpipinstallvirtualenv

Collectingvirtualenv

Usingcachedvirtualenvndash1510ndashpy2py3ndashnonendashanywhl

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

OnceyouhavevirtualenvinstalledyoursquollneedtomakeavenvsdirectoryandfillitwithavirtualenvironmentClickheretoviewcodeimage

gtmkdirvenvs

gtvirtualenvndashndashsystemndashsitendashpackagesvenvslpthw

Usingbaseprefix

cuserszedshappdatalocalprogramspythonpython36

Newpythonexecutablein

CUserszedshawvenvslpthwScriptspythonexe

Installingsetuptoolspipwheeldone

ThosetwocommandscreateavenvsfolderforstoringdifferentvirtualenvironmentsandthencreateyourfirstonenamedlpthwAvirtualenvironment(virtualenv)isaldquofakerdquoplacetoinstallsoftwaresothatyoucanhavedifferentversionsofdifferentpackagesforeachprojectyoursquoreworkingonOnceyouhavethevirtualenvsetupyouneedtoactivateitClickheretoviewcodeimage

gtvenvslpthwScriptsactivate

ThatwillruntheactivatescriptforPowerShellwhichconfiguresthelpthwvirtualenvforyourcurrentshellEverytimeyouwanttouseyoursoftwareforthebookyoursquollrunthiscommandYoursquollnoticeinournextcommandthatthereisnowa(lpthw)addedtothePowerShellpromptshowingyouwhichvirtualenvyoursquoreusingFinallyyoujustneedtoinstallnoseforrunningtestslaterClickheretoviewcodeimage

(lpthw)gtpipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB12MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)gt

YoursquollseethatthisinstallsnoseexceptpipwillinstallitintoyourvenvslpthwvirtualenvironmentinsteadofthemainsystempackagesdirectoryThisletsyouinstallconflictingversionsofPythonpackagesforeachprojectyouworkonwithoutinfectingyourmainsystemconfiguration

CreatingtheSkeletonProjectDirectoryFirstcreatethestructureofyourskeletondirectorywiththesecommands

$mkdirprojects

$cdprojects

$mkdirskeleton

$cdskeleton

$mkdirbinNAMEtestsdocs

IuseadirectorynamedprojectstostoreallthevariousthingsIrsquomworkingonInsidethatdirectoryIhavemyskeletondirectorythatIputthebasisofmyprojectsintoThedirectoryNAMEwillberenamedtowhateveryouarecallingyourprojectrsquosmainmodulewhenyouusetheskeletonNextweneedtosetupsomeinitialfilesHerersquoshowyoudothatonLinuxmacOS

$touchNAME__init__py

$touchtests__init__py

HerersquosthesamethingonWindowsPowerShellClickheretoviewcodeimage

$newndashitemndashtypefileNAME__init__py

$newndashitemndashtypefiletests__init__py

ThatcreatesanemptyPythonmoduledirectorywecanputourcodeinThenweneedtocreateasetuppyfilewecanusetoinstallourprojectlaterifwewantClickheretoviewcodeimage

setuppy

1try

2fromsetuptoolsimportsetup

3exceptImportError

4fromdistutilscoreimportsetup

5

6config=

7descriptionMyProject

8authorMyName

9urlURLtogetitat

10download_urlWheretodownloadit

11author_emailMyemail

12version01

13install_requires[nose]

14packages[NAME]

15scripts[]

16nameprojectname

17

18

19setup(config)

EditthisfilesothatithasyourcontactinformationandisreadytogoforwhenyoucopyitFinallyyouwillwantasimpleskeletonfilefortestsnamedtestsNAME_testspyClickheretoviewcodeimage

NAME_testspy

1fromnosetoolsimport

2importNAME

3

4defsetup()

5print(SETUP)

6

7defteardown()

8print(TEARDOWN)

9

10deftest_basic()

11print(IRAN)

FinalDirectoryStructureWhenyouaredonesettingallofthisupyourdirectoryshouldlooklikeminehere

skeleton

NAME

__init__py

bin

docs

setuppy

tests

NAME_testspy

__init__py

AndfromnowonyoushouldrunyourcommandsfromthisdirectoryIfyoucanrsquotdols-RandifyoudonrsquotseethissamestructurethenyouareinthewrongplaceForexamplepeoplecommonlygointothetestsdirectoryto

trytorunfilestherewhichwonrsquotworkTorunyourapplicationrsquostestsyouwouldneedtobeabovetestsandthislocationIhaveaboveSoifyoutrythisClickheretoviewcodeimage

$cdtestsWRONGWRONGWRONG

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran0testsin0000s

OK

ThatiswrongYouhavetobeabovetestssoassumingyoumadethismistakeyouwouldfixitbydoingthisClickheretoviewcodeimage

$cdgetoutoftests

$lsCORRECTyouarenowintherightspot

NAMEbindocssetuppytests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0004s

OK

Rememberthisbecausepeoplemakethismistakequitefrequently

WarningAtthetimeofpublicationIlearnedthatthenoseprojecthasbeenabandonedandmightnotworkwellIfyouhavestrangesyntaxerrorswhenyourunnoseteststhenlookattheerroroutputIfitreferencesldquopython27rdquointheoutputthenchancesarenosetestsistryingtorunthe27versionofPythononyourcomputerThesolutionistorunnoseusingpython36-mnoseonLinuxormacOSOnWindowsyoumaynothavethisproblembutusingpython-mnosewillsolveitifyoudo

TestingYourSetupAfteryougetallthatinstalledyoushouldbeabletodothis

$nosetests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0007s

OK

IrsquollexplainwhatthisnoseteststhingisdoinginthenextexercisebutfornowifyoudonotseethatyouprobablygotsomethingwrongMakesureyouput__init__pyfilesinyourNAMEandtestsdirectoriesandmakesureyougottestsNAME_testspyright

UsingtheSkeletonYouarenowdonewithmostofyouryakshavingWheneveryouwanttostartanewprojectjustdothis

1MakeacopyofyourskeletondirectoryNameitafteryournewproject2Rename(move)theNAMEdirectorytobethenameofyourprojectorwhateveryouwanttocallyourrootmodule

3Edityoursetuppytohavealltheinformationforyourproject4RenametestsNAME_testspytoalsohaveyourmodulename5Doublecheckitrsquosallworkingbyusingnosetestsagain6Startcoding

RequiredQuizThisexercisedoesnrsquothaveStudyDrillsinsteadherersquosquizyoushouldcomplete

1Readabouthowtouseallofthethingsyouinstalled2ReadaboutthesetuppyfileandallithastoofferWarningItisnotaverywell-writtenpieceofsoftwaresoitwillbeverystrangetouse

3Makeaprojectandstartputtingcodeintothemodulethengetthemoduleworking

4PutascriptinthebindirectorythatyoucanrunReadabouthowyoucanmakeaPythonscriptthatrsquosrunnableforyoursystem

5Mentionthebinscriptyoucreatedinyoursetuppysothatitgetsinstalled

6Useyoursetuppytoinstallyourownmoduleandmakesureitworksthenusepiptouninstallit

CommonStudentQuestions

CommonStudentQuestionsDotheseinstructionsworkonWindowsTheyshouldbutdependingontheversionofWindowsyoumayneedtostrugglewiththesetupabittogetitworkingJustkeepresearchingandtryingituntilyougetitorseeifyoucanaskamoreexperiencedPython+Windowsfriendtohelpout

WhatdoIputintheconfigdictionaryinmysetuppyMakesureyoureadthedocumentationfordistutilsathttpdocspythonorgdistutilssetupscripthtml

IcanrsquotseemtoloadtheNAMEmoduleandjustgetanImportErrorMakesurethatyoumadetheNAME__init__pyfileIfyoursquoreonWindowsmakesureyoudidnrsquotaccidentallynameitNAME__init__pytxtwhichhappensbydefaultwithsomeeditors

WhydoweneedabinfolderatallThisisjustastandardplacetoputscriptsthatarerunonthecommandlinenotaplacetoputmodules

MynosetestsrunonlyshowsonetestbeingrunIsthatrightYesthatrsquoswhatmyoutputshowstoo

Exercise47AutomatedTesting

HavingtotypecommandsintoyourgameoverandovertomakesureitrsquosworkingisannoyingWouldnrsquotitbebettertowritelittlepiecesofcodethattestyourcodeThenwhenyoumakeachangeoraddanewthingtoyourprogramyoujustldquorunyourtestsrdquoandthetestsmakesurethingsarestillworkingTheseautomatedtestswonrsquotcatchallyourbugsbuttheywillcutdownonthetimeyouspendrepeatedlytypingandrunningyourcodeEveryexerciseafterthisonewillnothaveaWhatYouShouldSeesectionbutinsteadwillhaveaWhatYouShouldTestsectionYouwillbewritingautomatedtestsforallofyourcodestartingnowandthiswillhopefullymakeyouanevenbetterprogrammerIwonrsquottrytoexplainwhyyoushouldwriteautomatedtestsIwillonlysaythatyouaretryingtobeaprogrammerandprogrammersautomateboringandtedioustasksTestingapieceofsoftwareisdefinitelyboringandtedioussoyoumightaswellwritealittlebitofcodetodoitforyouThatshouldbealltheexplanationyouneedbecauseyourreasonforwritingunittestsistomakeyourbrainstrongerYouhavegonethroughthisbookwritingcodetodothingsNowyouaregoingtotakethenextleapandwritecodethatknowsaboutothercodeyouhavewrittenThisprocessofwritingatestthatrunssomecodeyouhavewrittenforcesyoutounderstandclearlywhatyouhavejustwrittenItsolidifiesinyourbrainexactlywhatitdoesandwhyitworksandgivesyouanewlevelofattentiontodetail

WritingaTestCaseWersquoregoingtotakeaverysimplepieceofcodeandwriteonesimpletestWersquoregoingtobasethislittletestonanewprojectfromyourprojectskeletonFirstmakeanex47projectfromyourprojectskeletonHerearethestepsyoushouldtakeIrsquomgoingtogivetheseinstructionsinEnglishratherthanshowyouhowtotypethemsothatyouhavetofigureitout

1Copyskeletontoex472RenameeverythingwithNAMEtoex473ChangethewordNAMEinallthefilestoex474Finallyremoveallthepycfilestomakesureyoursquoreclean

ReferbacktoExercise46ifyougetstuckandifyoucanrsquotdothiseasilythen

maybepracticeitafewtimes

WarningRememberthatyourunthecommandnoseteststorunthetestsYoucanrunthemwithpython36ex47_testspybutitwonrsquotworkaseasilyandyoursquollhavetodoitforeachtestfile

Nextcreateasimplefileex47gamepywhereyoucanputthecodetotestThiswillbeaverysillylittleclassthatwewanttotestwiththiscodeinitClickheretoviewcodeimage

gamepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name

5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)Onceyouhavethatfile

changetheunittestskeletontothisClickheretoviewcodeimage

ex47_testspy

1fromnosetoolsimport

2fromex47gameimportRoom

3

4

5deftest_room()

6gold=Room(GoldRoom

7Thisroomhasgoldinityoucangrab

Theresa

8doortothenorth)

9assert_equal(goldnameGoldRoom)

10assert_equal(goldpaths)

11

12deftest_room_paths()

13center=Room(CenterTestroominthecenter)

14north=Room(NorthTestroominthenorth)

15south=Room(SouthTestroominthesouth)

16

17centeradd_paths(northnorthsouthsouth)

18assert_equal(centergo(north)north)

19assert_equal(centergo(south)south)

20

21deftest_map()

22start=Room(StartYoucangowestanddownahole)

23west=Room(TreesTherearetreeshereyoucango

east)

24down=Room(DungeonItsdarkdownhereyoucango

up)

25

26startadd_paths(westwestdowndown)

27westadd_paths(eaststart)

28downadd_paths(upstart)

29

30assert_equal(startgo(west)west)

31assert_equal(startgo(west)go(east)start)

32assert_equal(startgo(down)go(up)start)Thisfile

importstheRoomclassyoumadeintheex47gamemodulesothatyou

candotestsonitThereisthenasetofteststhatarefunctions

startingwithtest_Insideeachtestcasetherersquosabitofcodethat

makesaroomorasetofroomsandthenmakessuretheroomswork

thewayyouexpectthemtoworkIttestsoutthebasicroom

featuresthenthepathsthentriesoutawholemap

Theimportantfunctionshereareassert_equalwhichmakessurethatvariablesyouhavesetorpathsyouhavebuiltinaRoomareactuallywhatyouthinktheyareIfyougetthewrongresultthennosetestswillprintoutanerrormessagesoyoucangofigureitout

TestingGuidelinesFollowthisloosesetofguidelineswhenmakingyourtests

1TestfilesgointestsandarenamedBLAH_testspyotherwisenosetestswonrsquotrunthemThisalsokeepsyourtestsfromclashingwithyourothercode

2Writeonetestfileforeachmoduleyoumake3Keepyourtestcases(functions)shortbutdonotworryiftheyareabitmessyTestcasesareusuallykindofmessy

4EventhoughtestcasesaremessytrytokeepthemcleanandremoveanyrepetitivecodeyoucanCreatehelperfunctionsthatgetridofduplicatecodeYouwillthankmelaterwhenyoumakeachangeandthenhaveto

codeYouwillthankmelaterwhenyoumakeachangeandthenhavetochangeyourtestsDuplicatedcodewillmakechangingyourtestsmoredifficult

5FinallydonotgettooattachedtoyourtestsSometimesthebestwaytoredesignsomethingistojustdeleteitandstartover

WhatYouShouldSeeClickheretoviewcodeimage

Exercise47Session

$nosetests

---------------------------------------------------------------------

-

Ran3testsin0008s

OK

ThatrsquoswhatyoushouldseeifeverythingisworkingrightTrycausinganerrortoseewhatthatlookslikeandthenfixit

StudyDrills1Goreadaboutnosetestsmoreandalsoreadaboutalternatives2LearnaboutPythonrsquosldquodoctestsrdquoandseeifyoulikethembetter3Makeyourroommoreadvancedandthenuseittorebuildyourgameyetagainbutthistimeunittestasyougo

CommonStudentQuestionsIgetasyntaxerrorwhenIrunnosetestsIfyougetthatthenlookatwhattheerrorsaysandfixthatlineofcodeortheonesaboveitToolslikenosetestsarerunningyourcodeandthetestcodesotheywillfindsyntaxerrorsthesameasrunningPythonwill

Icanrsquotimportex47gameMakesureyoucreatetheex47__init__pyfileRefertoExercise46againtoseehowitrsquosdoneIfthatrsquosnottheproblemthendothisonmacOSLinuxexportPYTHONPATH=AndonWindowsClickheretoviewcodeimage

$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

FinallymakesureyoursquorerunningthetestswithnosetestsnotwithjustPython

IgetUserWarningwhenIrunnosetestsYouprobablyhavetwoversionsofPythoninstalledoryouarenrsquotusingdistributeGobackandinstalldistributeorpipasIdescribeinExercise46

Exercise48AdvancedUserInput

InpastgamesyouhandledtheuserrsquosinputbysimplyexpectingsetstringsIftheusertypedldquorunrdquoandexactlyldquorunrdquothenthegameworkedIftheytypedinsimilarphraseslikeldquorunfastrdquoitwouldfailWhatweneedisadevicethatletsuserstypephrasesinvariouswaysandthenconvertthatintosomethingthecomputerunderstandsForexamplewersquodliketohaveallofthesephrasesworkthesamebullopendoorbullopenthedoorbullgoTHROUGHthedoorbullpunchbearbullPunchTheBearintheFACEItshouldbealrightforausertowritesomethingalotlikeEnglishforyourgameandhaveyourgamefigureoutwhatitmeansTodothiswersquoregoingtowriteamodulethatdoesjustthatThismodulewillhaveafewclassesthatworktogethertohandleuserinputandconvertitintosomethingyourgamecanworkwithreliablyAsimplifiedversionoftheEnglishlanguagecouldincludethefollowingelementsbullWordsseparatedbyspacesbullSentencescomposedofthewordsbullGrammarthatstructuresthesentencesintomeaningThatmeansthebestplacetostartisfiguringouthowtogetwordsfromtheuserandwhatkindsofwordsthoseare

OurGameLexiconInourgamewehavetocreatealistofallowablewordscalledaldquolexiconrdquo

bullDirectionwordsnorthsoutheastwestdownupleftrightbackbullVerbsgostopkilleatbullStopwordstheinoffromatitbullNounsdoorbearprincesscabinetbullNumbersanystringof0through9charactersWhenwegettonounswehaveaslightproblemsinceeachroomcouldhaveadifferentsetofnounsbutletrsquosjustpickthissmallsettoworkwithfornowandimproveitlater

BreakingUpaSentenceOncewehaveourlexiconweneedawaytobreakupsentencessothatwecanfigureoutwhattheyareInourcasewersquovedefinedasentenceasldquowordsseparatedbyspacesrdquosowereallyjustneedtodothis

stuff=input(gt)

words=stuffsplit()Thatrsquosallwersquollworryaboutfornowbutthis

willworkreallywellforquiteawhile

LexiconTuples

LexiconTuplesOnceweknowhowtobreakupasentenceintowordswejusthavetogothroughthelistofwordsandfigureoutwhatldquotyperdquotheyareTodothatwersquoregoingtouseahandylittlePythonstructurecalledaldquotuplerdquoAtupleisnothingmorethanalistthatyoucanrsquotmodifyItrsquoscreatedbyputtingdatainsideasetofparentheseswithacommalikealistClickheretoviewcodeimage

first_word=(verbgo)

second_word=(directionnorth)

third_word=(directionwest)

sentence=[first_wordsecond_wordthird_word]

Thiscreatesapair(TYPEWORD)thatletsyoulookatthewordanddothingswithitThisisjustanexamplebutthatrsquosbasicallytheendresultYouwanttotakerawinputfromtheusercarveitintowordswithsplitanalyzethosewordstoidentifytheirtypesandfinallymakeasentenceoutofthem

ScanningInputNowyouarereadytowriteyourscannerThisscannerwilltakeastringofrawinputfromauserandreturnasentencethatrsquoscomposedofalistoftupleswiththe(TOKENWORD)pairingsIfawordisnrsquotpartofthelexiconthenitshouldstillreturntheWORDbutsettheTOKENtoanerrortokenTheseerrortokenswilltelluserstheymessedupHerersquoswhereitgetsfunIrsquomnotgoingtotellyouhowtodothisInsteadIrsquomgoingtowritealdquounittestrdquoandyouaregoingtowritethescannersothattheunittestworks

ExceptionsandNumbersThereisonetinythingIwillhelpyouwithfirstandthatrsquosconvertingnumbersInordertodothisthoughwersquoregoingtocheatanduseexceptionsAnexceptionisanerrorthatyougetfromsomefunctionyoumayhaverunWhathappensisyourfunctionldquoraisesrdquoanexceptionwhenitencountersanerrorthenyouhavetohandlethatexceptionForexampleifyoutypethisintoPythonyougetanexceptionClickheretoviewcodeimage

Exercise48PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtint(hell)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

ValueErrorinvalidliteralforint()withbase10hell

ThatValueErrorisanexceptionthattheint()functionthrewbecausewhatyouhandedint()isnotanumberTheint())functioncouldhavereturnedavaluetotellyouithadanerrorbutsinceitonlyreturnsintegersitrsquodhaveahardtimedoingthatItcanrsquotreturn-1sincethatrsquosanumberInsteadoftryingtofigureoutwhattoreturnwhentherersquosanerrortheint()functionraisestheValueErrorexceptionandyoudealwithitYoudealwithanexceptionbyusingthetryandexceptkeywordsex48_convertpy

1defconvert_number(s)

2try

3returnint(s)

4exceptValueError

5returnNoneYouputthecodeyouwanttoldquotryrdquoinside

thetryblockandthenyouputthecodetorunfortheerrorinside

theexceptInthiscasewewanttoldquotryrdquotocallint()onsomething

thatmightbeanumberIfthathasanerrorthenweldquocatchrdquoitand

returnNone

InyourscannerthatyouwriteyoushouldusethisfunctiontotestwhethersomethingisanumberYoushouldalsodoitasthelastthingyoucheckforbeforedeclaringthatwordanerrorword

ATestFirstChallengeTestfirstisaprogrammingtacticwhereyouwriteanautomatedtestthatpretendsthecodeworksthenyouwritethecodetomakethetestactuallyworkThismethodworkswhenyoucanrsquotvisualizehowthecodeisimplementedbutyoucanimaginehowyouhavetoworkwithitForexampleifyouknowhowyouneedtouseanewclassinanothermodulebutyoudonrsquotquiteknowhowtoimplementthatclassyetthenwritethetestfirstYouaregoingtotakeatestIgiveyouanduseittowritethecodethatmakesitworkTodothisexercisefollowthisprocedure1CreateonesmallpartofthetestIgiveyou

2Makesureitrunsandfailssoyouknowthatthetestisactuallyconfirmingafeatureworks

3Gotoyoursourcefilelexiconpyandwritethecodethatmakesthistestpass

4RepeatuntilyouhaveimplementedeverythinginthetestWhenyougettostep3itrsquosalsogoodtocombineourothermethodofwritingcode1Maketheldquoskeletonrdquofunctionorclassthatyouneed

2Writecommentsinsidedescribinghowthatfunctionworks3Writethecodethatdoeswhatthecommentsdescribe4Removeanycommentsthatjustrepeatthecode

ThismethodofwritingcodeiscalledldquopsuedocoderdquoandworkswellifyoudonrsquotknowhowtoimplementsomethingbutyoucandescribeitinyourownwordsCombiningtheldquotestfirstrdquowiththeldquopsuedocoderdquotacticswehavethissimpleprocessforprogramming1Writeabitoftestthatfails

2Writetheskeletonfunctionmoduleclassthetestneeds3Filltheskeletonwithcommentsinyourownwordsexplaininghowitworks

4Replacethecommentswithcodeuntilthetestpasses5Repeat

InthisexerciseyouwillpracticethismethodofworkingbymakingatestIgiveyourunagainstthelexiconpymodule

WhatYouShouldTestHereisthetestcasetestslexicon_testspythatyoushouldusebutdonrsquottypethisinyetClickheretoviewcodeimage

lexicon_testspy

1fromnosetoolsimport

2fromex48importlexicon

3

4

5deftest_directions()

6assert_equal(lexiconscan(north)[(direction

north)])

7result=lexiconscan(northsoutheast)

8assert_equal(result[(directionnorth)

9(directionsouth)

10(directioneast)])

11

12deftest_verbs()

13assert_equal(lexiconscan(go)[(verbgo)])

14result=lexiconscan(gokilleat)

15assert_equal(result[(verbgo)

16(verbkill)

17(verbeat)])

18

19

20deftest_stops()

21assert_equal(lexiconscan(the)[(stopthe)])

22result=lexiconscan(theinof)

23assert_equal(result[(stopthe)

24(stopin)

25(stopof)])

26

27

28deftest_nouns()

29assert_equal(lexiconscan(bear)[(nounbear)])

30result=lexiconscan(bearprincess)

31assert_equal(result[(nounbear)

32(nounprincess)])

33

34deftest_numbers()

35assert_equal(lexiconscan(1234)[(number1234)])

36result=lexiconscan(391234)

37assert_equal(result[(number3)

38(number91234)])

39

40

41deftest_errors()

42assert_equal(lexiconscan(ASDFADFASDF)

43[(errorASDFADFASDF)])

44result=lexiconscan(bearIASprincess)

45assert_equal(result[(nounbear)

46(errorIAS)

47(nounprincess)])Youwillwant

tocreateanewprojectusingtheprojectskeletonjustlikeyoudid

inExercise47Thenyoursquollneedtocreatethistestcaseandthe

lexiconpyfileitwilluseLookatthetopofthetestcasetosee

howitrsquosbeingimportedtofigureoutwhereitgoes

NextfollowtheprocedureIgaveyouandwritealittlebitofthetestcaseatatimeForexampleherersquoshowIrsquoddoit1WritetheimportatthetopGetthattowork

2Createanemptyversionofthefirsttestcasetest_directionsMakesurethatruns

3Writethefirstlineofthetest_directionstestcaseMakeitfail4Gotothelexiconpyfileandcreateanemptyscanfunction5Runthetestandmakesurescanisatleastrunningeventhoughitfails6Fillinpsuedocodecommentsforhowscanshouldworktomaketest_directionspass

7Writethecodethatmatchesthecommentsuntiltest_directionspasses

8Gobacktotest_directionsandwritetherestofthelines9Gobacktoscaninlexiconpyandworkonittomakethisnewtestcodepass

10Onceyoursquovedonethatyouhaveyourfirstpassingtestandyoumoveontothenexttest

AslongasyoukeepfollowingthisprocedureonelittlechunkatatimeyoucansuccessfullyturnalargeproblemintosmallersolvableproblemsItrsquoslikeclimbingamountainbyturningitintoabunchoflittlehills

StudyDrills1Improvetheunittesttomakesureyoutestmoreofthelexicon2Addtothelexiconandthenupdatetheunittest3MakesureyourscannerhandlesuserinputinanycapitalizationandcaseUpdatethetesttomakesurethisactuallyworks

4Findanotherwaytoconvertthenumber5Mysolutionwas37lineslongIsyourslongerShorter

CommonStudentQuestionsWhydoIkeepgettingImportErrorsImporterrorsareusuallycausedbyfourthings1Youdidnrsquotmakean__init__pyinadirectorythathasmodulesinit2Youareinthewrongdirectory3Youareimportingthewrongmodulebecauseyouspelleditwrong4YourPYTHONPATHisnrsquotsettosoyoucanrsquotloadmodulesfromyourcurrentdirectory

Whatrsquosthedifferencebetweentry-exceptandif-elseThe

try-exceptconstructisonlyusedforhandlingexceptionsthatmodulescanthrowItshouldneverbeusedasanalternativetoif-else

IsthereawaytokeepthegamerunningwhiletheuseriswaitingtotypeIrsquomassumingyouwanttohaveamonsterattackusersiftheydonrsquotreactquicklyenoughItispossiblebutitinvolvesmodulesandtechniquesthatareoutsideofthisbookrsquosdomain

Exercise49MakingSentences

WhatweshouldbeabletogetfromourlittlegamelexiconscannerisalistthatlookslikethisClickheretoviewcodeimage

Exercise49PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48importlexicon

gtgtgtlexiconscan(gonorth)

[(verbgo)(directionnorth)]

gtgtgtlexiconscan(killtheprincess)

[(verbkill)(stopthe)(nounprincess)]

gtgtgtlexiconscan(eatthebear)

[(verbeat)(stopthe)(nounbear)]

Thiswillalsoworkonlongersentencessuchaslexiconscan(openthedoorandsmackthebearinthenose)NowletusturnthisintosomethingthegamecanworkwithwhichwouldbesomekindofSentenceclassIfyouremembergradeschoolasentencecanbeasimplestructurelikeSubjectVerbObjectObviouslyitgetsmorecomplexthanthatandyouprobablydidmanydaysofannoyingsentencediagramsforEnglishclassWhatwewantistoturntheprecedinglistsoftuplesintoaniceSentenceobjectthathassubjectverbandobject

MatchandPeekTodothisweneedfivetools

1AwaytoloopthroughthelistofscannedwordsThatrsquoseasy2AwaytoldquomatchrdquodifferenttypesoftuplesthatweexpectinourSubjectVerbObjectsetup

3Awaytoldquopeekrdquoatapotentialtuplesowecanmakesomedecisions4Awaytoldquoskiprdquothingswedonotcareaboutlikestopwords5ASentenceobjecttoputtheresultsin

Wewillbeputtingthesefunctionsinamodulenamedex48parserinafilenamedex48parserpyinordertotestitWeusethepeekfunctiontosay

ldquolookatthenextelementinourtuplelistandthenmatchtotakeoneoffandworkwithitrdquo

TheSentenceGrammarBeforeyoucanwritethecodeyouneedtounderstandhowbasicEnglishsentencegrammarworksInourparserwewanttoproduceaSentenceobjectthathasthreeattributes

SentencesubjectThisisthesubjectofanysentencebutcoulddefaulttoldquoplayerrdquomostofthetimesinceasentenceofldquorunnorthrdquoisimplyingldquoplayerrunnorthrdquoThiswillbeanoun

SentenceverbThisistheactionofthesentenceInldquorunnorthrdquoitwouldbeldquorunrdquoThiswillbeaverb

SentenceobjectThisisanothernounthatreferstowhattheverbisdoneonInourgameweseparateoutdirectionswhichwouldalsobeobjectsInldquorunnorthrdquothewordldquonorthrdquowouldbetheobjectInldquohitbearrdquothewordldquobearrdquowouldbetheobject

OurparserthenhastousethefunctionswedescribedandgivenascannedsentenceconvertitintoanListofSentenceobjectstomatchtheinput

AWordonExceptionsYoubrieflylearnedaboutexceptionsbutnothowtoraisethemThiscodedemonstrateshowtodothatwiththeParserErroratthetopNoticethatitusesclassestogiveitthetypeofExceptionAlsonoticetheuseoftheraisekeywordtoraisetheexceptionInyourtestsyouwillwanttoworkwiththeseexceptionswhichIrsquollshowyouhowtodo

TheParserCodeIfyouwantanextrachallengestoprightnowandtrytowritethisbasedonjustmydescriptionIfyougetstuckyoucancomebackandseehowIdiditbuttryingtoimplementtheparseryourselfisgoodpracticeIwillnowwalkthroughthecodesoyoucanenteritintoyourex48parserpyWestarttheparserwiththeexceptionweneedforaparsingerrorClickheretoviewcodeimage

parserpy

1classParserError(Exception)

2pass

ThisishowyoumakeyourownParserErrorexceptionclassyoucanthrowNextweneedtheSentenceobjectwersquollcreateClickheretoviewcodeimage

parserpy

1classSentence(object)

2

3def__init__(selfsubjectverbobj)

4rememberwetake(nounprincess)tuplesand

convertthem

5selfsubject=subject[1]

6selfverb=verb[1]

7selfobject=obj[1]

TherersquosnothingspecialaboutthiscodesofarYoursquorejustmakingsimpleclassesInourdescriptionoftheproblemweneedafunctionthatcanpeekatalistofwordsandreturnwhattypeofworditisClickheretoviewcodeimage

parserpy

1defpeek(word_list)

2ifword_list

3word=word_list[0]

4returnword[0]

5else

6returnNoneWeneedthisfunctionbecausewersquollhaveto

makedecisionsaboutwhatkindofsentencewersquoredealingwithbased

onwhatthenextwordisThenwecancallanotherfunctionto

consumethatwordandcarryon

ToconsumeawordweusethematchfunctionwhichconfirmsthattheexpectedwordistherighttypetakesitoffthelistandreturnsthewordClickheretoviewcodeimage

parserpy

1defmatch(word_listexpecting)

2ifword_list

3word=word_listpop(0)

4

5ifword[0]==expecting

6returnword

7else

8returnNone

9else

10returnNoneAgainthisisfairlysimplebutmakesure

youunderstandthiscodeAlsomakesureyouunderstandwhyIrsquomdoing

itthiswayIneedtopeekatwordsinthelisttodecidewhatkind

ofsentenceIrsquomdealingwithandthenIneedtomatchthosewordsto

createmySentence

ThelastthingIneedisawaytoskipwordsthatarenrsquotusefultotheSentenceThesearethewordslabeledldquostopwordsrdquo(typestop)thatarewordslikeldquotherdquoldquoandrdquoandldquoardquoClickheretoviewcodeimage

parserpy

1defskip(word_listword_type)

2whilepeek(word_list)==word_type

3match(word_listword_type)Rememberthatskipdoesnrsquot

skiponeworditskipsasmanywordsofthattypeasitfindsThis

makesitsoifsomeonetypesldquoscreamatthebearrdquoyougetldquoscreamrdquo

andldquobearrdquo

ThatrsquosourbasicsetofparsingfunctionsandwiththatwecanactuallyparsejustaboutanytextwewantOurparserisverysimplethoughsotheremainingfunctionsareshortFirstwecanhandleparsingaverbClickheretoviewcodeimage

parserpy

1defparse_verb(word_list)

2skip(word_liststop)

3

4ifpeek(word_list)==verb

5returnmatch(word_listverb)

6else

7raiseParserError(Expectedaverbnext)Weskipany

stopwordsthenpeekaheadtomakesurethenextwordisaldquoverbrdquo

typeIfitrsquosnotthenraisetheParserErrortosaywhyIfitisa

ldquoverbrdquothenmatchitwhichtakesitoffthelistAsimilar

functionhandlessentenceobjectsClickheretoviewcodeimage

parserpy

1defparse_object(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==direction

8returnmatch(word_listdirection)

9else

10raiseParserError(Expectedanounordirectionnext)

Againskipthestopwordspeekaheadanddecideifthesentenceis

correctbasedonwhatrsquosthereIntheparse_objectfunctionthough

weneedtohandlebothldquonounrdquoandldquodirectionrdquowordsaspossible

objectsSubjectsarethensimilaragainbutsincewewanttohandle

theimpliedldquoplayerrdquonounwehavetousepeekClickheretoview

codeimage

parserpy

1defparse_subject(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==verb

8return(nounplayer)

9else

10raiseParserError(Expectedaverbnext)Withthat

alloutofthewayandreadyourfinalparse_sentencefunctionis

verysimpleClickheretoviewcodeimage

parserpy

1defparse_sentence(word_list)

2subj=parse_subject(word_list)

3verb=parse_verb(word_list)

4obj=parse_object(word_list)

5

6returnSentence(subjverbobj)

PlayingwiththeParserToseehowthisworksyoucanplaywithitlikethis

ToseehowthisworksyoucanplaywithitlikethisClickheretoviewcodeimage

Exercise49aPythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48parserimport

gtgtgtx=parse_sentence([(verbrun)(directionnorth)])

gtgtgtxsubject

player

gtgtgtxverb

run

gtgtgtxobject

north

gtgtgtx=parse_sentence([(nounbear)(verbeat)(stop

the)

(nounhoney)])

gtgtgtxsubject

bear

gtgtgtxverb

eat

gtgtgtxobject

honey

TrytomapsentencestothecorrectpairingsinasentenceForexamplehowwouldyousayldquothebearrunsouthrdquo

WhatYouShouldTestForExercise49writeacompletetestthatconfirmseverythinginthiscodeisworkingPutthetestintestsparser_testspysimilartothetestfilefromthelastexerciseThatincludesmakingexceptionshappenbygivingtheparserbadsentencesCheckforanexceptionbyusingthefunctionassert_raisesfromthenosedocumentationLearnhowtousethissoyoucanwriteatestthatisexpectedtofailwhichisveryimportantintestingLearnaboutthisfunction(andothers)byreadingthenosedocumentationWhenyouaredoneyoushouldknowhowthisbitofcodeworksandhowtowriteatestforotherpeoplersquoscodeeveniftheydonotwantyoutoTrustmeitrsquosaveryhandyskilltohave

StudyDrills

StudyDrills1Changetheparse_methodsandtrytoputthemintoaclassratherthanusethemjustasmethodsWhichdesigndoyoulikebetter

2Maketheparsermoreerror-resistantsothatyoucanavoidannoyingyourusersiftheytypewordsyourlexicondoesnrsquotunderstand

3Improvethegrammarbyhandlingmorethingslikenumbers4ThinkabouthowyoumightusethisSentenceclassinyourgametodomorefunthingswithauserrsquosinput

CommonStudentQuestionsIcanrsquotseemtomakeassert_raisesworkrightMakesureyouarewritingassert_raises(exceptioncallableparameters)andnotwritingassert_raises(exceptioncallable(parameters))Noticehowthesecondformiscallingthefunctionthenpassingtheresulttoassert_raiseswhichiswrongYouhavetopassthefunctiontocallanditsargumentstoassert_raises

Exercise50YourFirstWebsite

ThesefinalthreeexerciseswillbeveryhardandyoushouldtakeyourtimewiththemInthisfirstoneyoursquollbuildasimplewebversionofoneofyourgamesBeforeyouattemptthisexerciseyoumusthavecompletedExercise46successfullyandhaveaworkingpipinstalledsuchthatyoucaninstallpackagesandknowhowtomakeaskeletonprojectdirectoryIfyoudonrsquotrememberhowtodothisgobacktoExercise46anddoitalloveragain

InstallingflaskBeforecreatingyourfirstwebapplicationyoursquollfirstneedtoinstalltheldquowebframeworkrdquocalledflaskThetermldquoframeworkrdquogenerallymeansldquosomepackagethatmakesiteasierformetodosomethingrdquoIntheworldofwebapplicationspeoplecreateldquowebframeworksrdquotocompensateforthedifficultproblemstheyrsquoveencounteredwhenmakingtheirownsitesTheysharethesecommonsolutionsintheformofapackageyoucandownloadtobootstrapyourownprojectsInourcasewersquollbeusingtheflaskframeworkbuttherearemanymanymanyothersyoucanchoosefromFornowlearnflaskthenbranchouttoanotheronewhenyoursquoreready(orjustkeepusingflasksinceitrsquosgoodenough)UsingpipinstallflaskClickheretoviewcodeimage

$sudopipinstallflask

[sudo]passwordforzedshaw

Downloadingunpackingflask

Runningsetuppyegg_infoforpackageflask

Installingcollectedpackagesflask

Runningsetuppyinstallforflask

Successfullyinstalledflask

Cleaningup

ThiswillworkonLinuxandmacOScomputersbutonWindowsjustdropthesudopartofthepipinstallcommandanditshouldworkIfnotgobacktoExercise46andmakesureyoucandoitreliably

MakeaSimpleldquoHelloWorldrdquoProject

NowyoursquoregoingtomakeaninitialverysimpleldquoHelloWorldrdquowebapplicationandprojectdirectoryusingflaskFirstmakeyourprojectdirectoryClickheretoviewcodeimage

$cdprojects

$mkdirgothonweb

$cdgothonweb

$mkdirbingothonwebtestsdocstemplates

$touchgothonweb__init__py

$touchtests__init__py

YoursquollbetakingthegamefromExercise43andmakingitintoawebapplicationsothatrsquoswhyyoursquorecallingitgothonwebBeforeyoudothatweneedtocreatethemostbasicflaskapplicationpossiblePutthefollowingcodeintoapppyClickheretoviewcodeimage

ex50py

1fromflaskimportFlask

2app=Flask(__name__)

3

4approute()

5defhello_world()

6returnHelloWorld

7

8if__name__==__main__

9apprun()ThenruntheapplicationlikethisClickhereto

viewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)Finally

useyourwebbrowserandgotohttplocalhost5000andyoushould

seetwothingsFirstinyourbrowseryoursquollseeHelloworld

SecondyoursquollseeyourTerminalwithnewoutputlikethisClick

heretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

127001ndashndash[22Feb2017142850]GETHTTP11200ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

ThosearelogmessagesthatflaskprintsoutsoyoucanseethattheserverisworkingandwhatthebrowserisdoingbehindthescenesThelogmessageshelpyoudebugandfigureoutwhenyouhaveproblemsForexampleitrsquossayingthatyourbrowsertriedtogetfaviconicobutthatfiledidnrsquotexistsoit

returnedthe404NotFoundstatuscodeIhavenrsquotexplainedthewayanyofthiswebstuffworksyetbecauseIwanttogetyousetupandreadytorollsothatIcanexplainitbetterinthenexttwoexercisesToaccomplishthisIrsquollhaveyoubreakyourflaskapplicationinvariouswaysandthenrestructureitsothatyouknowhowitrsquossetup

WhatrsquosGoingOnHerersquoswhatrsquoshappeningwhenyourbrowserhitsyourapplication

1YourbrowsermakesanetworkconnectiontoyourowncomputerwhichiscalledlocalhostandisastandardwayofsayingldquowhatevermyowncomputeriscalledonthenetworkrdquoItalsousesport5000

2OnceitconnectsitmakesanHTTPrequesttotheapppyapplicationandasksfortheURLwhichiscommonlythefirstURLonanywebsite

3InsideapppyyoursquovegotalistofURLsandwhatfunctionstheymatchTheonlyonewehaveistheindexmappingThismeansthatwheneversomeonegoestowithabrowserflaskwillfindthedefindexandrunittohandletherequest

4NowthatflaskhasfounddefindexitcallsittoactuallyhandletherequestThisfunctionrunsandsimplyreturnsastringforwhatflaskshouldsendtothebrowser

5Finallyflaskhashandledtherequestandsendsthisresponsetothebrowserwhichiswhatyouareseeing

MakesureyoureallyunderstandthisDrawupadiagramofhowthisinformationflowsfromyourbrowsertoflaskthentodefindexandbacktoyourbrowser

FixingErrorsFirstdeleteline8whereyouassignthegreetingvariablethenhitrefreshinyourbrowserThenuseCTRL-CtokillflaskandstartitagainOnceitrsquosrunningagainrefreshyourbrowserandyoushouldseeanldquoInternalServerErrorrdquoBackinyourTerminalyoursquollseethis([VENV]isthepathtoyourvenvsdirectory)Clickheretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

[2017ndash02ndash22143554256]ERRORinappExceptionon[GET]

Traceback(mostrecentcalllast)

File[VENV]site-packagesflaskapppy

line1982inwsgi_app

response=selffull_dispatch_request()

File[VENV]site-packagesflaskapppy

line1614infull_dispatch_request

rv=selfhandle_user_exception(e)

File[VENV]site-packagesflaskapppy

line1517inhandle_user_exception

reraise(exc_typeexc_valuetb)

File[VENV]site-packagesflask_compatpy

line33inreraise

raisevalue

File[VENV]site-packagesflaskapppy

line1612infull_dispatch_request

rv=selfdispatch_request()

File[VENV]site-packagesflaskapppy

line1598indispatch_request

returnselfview_functions[ruleendpoint](reqview_args)

Fileapppyline8inindex

returnrender_template(indexhtmlgreeting=greeting)

NameErrornamegreetingisnotdefined

127001ndashndash[22Feb2017143554]GETHTTP11500ndash

ThisworkswellenoughbutyoucanalsorunflaskinldquodebuggermoderdquoThiswillgiveyouabettererrorpageandmoreusefulinformationTheproblemwithdebuggermodeisitrsquosnotsafetorunontheinternetsoyouhavetoexplicitlyturnitonlikethisClickheretoviewcodeimage

(lpthw)$exportFLASK_DEBUG=1

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

Restartingwithstat

Debuggerisactive

Debuggerpincode222ndash752ndash342

Afterthisyouhitrefreshinyourbrowserandyougetamuchmoredetailedpagewithinformationyoucanusetodebugtheapplicationandaliveconsoletoworkwithtofindoutmore

WarningItrsquostheflasklivedebuggingconsoleandtheimprovedoutputthatmakesdebugmodesodangerousontheinternetWiththisinformationanattackercancompletelycontrolyourmachineremotelyIfyoueverdoplaceyourwebapplicationontheinternetdonotactivatedebuggermodeInfactIwouldavoid

makingFLASK_DEBUGeasytoactivateItrsquostemptingtosimplyhackthisstartupsothatyousaveastepduringdevelopmentbutthenthathackwillgetontoyourwebserveranditrsquollturnintoarealhacknotjustsomethinglazyyoudidonenightwhenyouweretired

CreateBasicTemplatesYoucanbreakyourflaskapplicationbutdidyounoticethatldquoHelloWorldrdquoisnrsquotaverygoodHTMLpageThisisawebapplicationandassuchitneedsaproperHTMLresponseTodothatyouwillcreateasimpletemplatethatsaysldquoHelloWorldrdquoinabiggreenfontThefirststepistocreateatemplatesindexhtmlfilethatlookslikethisClickheretoviewcodeimage

indexhtml

lthtmlgt

ltheadgt

lttitlegtGothonsOfPlanetPercal25lttitlegt

ltheadgt

ltbodygt

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

ltbodygt

lthtmlgtIfyouknowwhatHTMListhenthisshouldlookfairly

familiarIfnotresearchHTMLandtrywritingafewwebpagesby

handsoyouknowhowitworksThisHTMLfilehoweverisa

templatewhichmeansthatflaskwillfillinldquoholesrdquointhetext

dependingonvariablesyoupassintothetemplateEveryplaceyou

see$greetingwillbeavariableyoursquollpasstothetemplatethat

altersitscontents

TomakeyourapppydothisyouneedtoaddsomecodetotellflaskwheretoloadthetemplateandtorenderitTakethatfileandchangeitlikethisClickheretoviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3

4app=Flask(__name__)

5

6approute()

7defindex()

8greeting=HelloWorld

9returnrender_template(indexhtmlgreeting=greeting)

10

11if__name__==__main__

12apprun()Paycloseattentiontothenewrendervariable

andhowIchangedthelastlineofindexGETsoitreturns

renderindex()passinginyourgreetingvariable

OnceyouhavethatinplacereloadthewebpageinyourbrowserandyoushouldseeadifferentmessageingreenYoushouldalsobeabletodoaViewSourceonthepageinyourbrowsertoseethatitisvalidHTMLThismayhaveflownbyyouveryfastsoletmeexplainhowatemplateworks1Inyourapppyyoursquoveimportedanewfunctionnamedrender_templateatthetop

2Thisrender_templateknowshowtoloadhtmlfilesoutofthetemplatesdirectorybecausethatisthedefaultmagicsettingforaflaskapplication

3Laterinyourcodewhenthebrowserhitsthedefindexinsteadofjustreturningthestringgreetingyoucallrender_templateandpassthegreetingtoitasavariable

4Thisrender_templatemethodthenloadsthetemplatesindexhtmlfile(eventhoughyoudidnrsquotexplicitlysaytemplates)andprocessesit

5InthistemplatesindexhtmlfileyouhavewhatlookslikenormalHTMLbutthentherersquosldquocoderdquoplacedbetweentwokindsofmarkersOneiswhichmarkspiecesofldquoexecutablecoderdquo(if-statementsfor-loopsetc)TheotheriswhichmarksvariablestobeconvertedintotextandplacedintotheHTMLoutputTheexecutablecodedoesnrsquotshowupintheHTMLTolearnmoreaboutthistemplatelanguagereadtheJinja2documentation

TogetdeeperintothischangethegreetingvariableandtheHTMLtoseewhateffectithasAlsocreateanothertemplatenamedtemplatesfoohtmlandrenderthatlikebefore

StudyDrills1Readthedocumentationathttpflaskpocooorgdocs012whichisthesameastheflaskproject

2Experimentwitheverythingyoucanfindthereincludingtheirexamplecode

3ReadaboutHTML5andCSS3andmakesomeotherhtmlandcssfilesforpractice

4IfyouhaveafriendwhoknowsDjangoandiswillingtohelpyouthenconsiderdoingExercises5051and52inDjangoinsteadtoseewhatthatrsquoslike

CommonStudentQuestionsIcanrsquotseemtoconnecttohttplocalhost5000Tryhttp1270015000instead

WhatisthedifferencebetweeflaskandwebpyNodifferenceIsimplyldquolockedrdquowebpyataparticularversionsothatitwouldbeconsistentforstudentsthennameditflaskLaterversionsofwebpymightbedifferentfromthisversion

Icanrsquotfindindexhtml(orjustaboutanything)YouprobablyaredoingcdbinfirstandthentryingtoworkwiththeprojectDonotdothisAllofthecommandsandinstructionsassumeyouareonedirectoryabovebinsoifyoucanrsquottypepython36apppythenyouareinthewrongdirectory

Whydoweassigngreeting=greetingwhenwecallthetemplateYouarenotassigningtogreetingYouaresettinganamedparametertogivetothetemplateItrsquossortofanassignmentbutitonlyaffectsthecalltothetemplatefunction

Icanrsquotuseport5000onmycomputerYouprobablyhaveananti-virusprograminstalledthatisusingthatportTryadifferentport

AfterinstallingflaskIgetImportErrorNomodulenamedwebYoumostlikelyhavemultipleversionsofpythoninstalledandareusingthewrongoneoryoudidnrsquotdotheinstall

correctlybecauseofanoldversionofpipTryuninstallingflaskandreinstallingitIfthatdoesnrsquotworkmaketriplesureyoursquoreusingtherightversionofpython

Exercise51GettingInputfromaBrowser

WhileitrsquosexcitingtoseethebrowserdisplayldquoHelloWorldrdquoitrsquosevenmoreexcitingtolettheusersubmittexttoyourapplicationfromaformInthisexercisewersquollimproveourstarterwebapplicationbyusingformsandstoringinformationaboutusersintotheirldquosessionsrdquo

HowtheWebWorksTimeforsomeboringstuffYouneedtounderstandabitmoreabouthowthewebworksbeforeyoucanmakeaformThisdescriptionisnrsquotcompletebutitrsquosaccurateandwillhelpyoufigureoutwhatmightbegoingwrongwithyourapplicationAlsocreatingformswillbeeasierifyouknowwhattheydoIrsquollstartwithasimplediagramthatshowsyouthedifferentpartsofawebrequestandhowtheinformationflows

IrsquovelabeledthelineswithletterssoIcanwalkyouthrougharegularrequestprocess1Youtypeintheurlhttptestcomintoyourbrowseranditsendstherequestonline(A)toyourcomputerrsquosnetworkinterface

2Yourrequestgoesoutovertheinternetonline(B)andthentotheremotecomputeronline(C)wheremyserveracceptstherequest

3Oncemycomputeracceptsitmywebapplicationgetsitonline(D)andmyPythoncoderunstheindexGEThandler

4TheresponsecomesoutofmyPythonserverwhenIreturnitandit

goesbacktoyourbrowseroverline(D)again5Theserverrunningthissitetakestheresponseoffline(D)thensendsitbackovertheinternetonline(C)

6Theresponsefromtheserverthencomesofftheinternetonline(B)andyourcomputerrsquosnetworkinterfacehandsittoyourbrowseronline(A)

7FinallyyourbrowserthendisplaystheresponseInthisdescriptionthereareafewtermsyoushouldknowsothatyouhaveacommonvocabularytoworkwithwhentalkingaboutyourwebapplicationBrowserThesoftwarethatyoursquoreprobablyusingeverydayMostpeopledonrsquotknowwhatabrowserreallydoesTheyjustcallbrowsersldquotheinternetrdquoItsjobistotakeaddresses(likehttptestcom)youtypeintotheURLbarthenusethatinformationtomakerequeststotheserveratthataddress

AddressThisisnormallyaURL(UniformResourceLocator)likehttptestcomandindicateswhereabrowsershouldgoThefirstparthttpindicatestheprotocolyouwanttouseinthiscaseldquoHyper-TextTransportProtocolrdquoYoucanalsotryftpibiblioorgtoseehowldquoFileTransportProtocolrdquoworksThehttptestcompartistheldquohostnamerdquoahumanreadableaddressyoucanrememberandwhichmapstoanumbercalledanIPaddresssimilartoatelephonenumberforacomputerontheinternetFinallyURLscanhaveatrailingpathlikethebookpartofhttptestcombookwhichindicatesafileorsomeresourceontheservertoretrievewitharequestTherearemanyotherpartsbutthosearethemainones

ConnectionOnceabrowserknowswhatprotocolyouwanttouse(http)whatserveryouwanttotalkto(httptestcom)andwhatresourceonthatservertogetitmustmakeaconnectionThebrowsersimplyasksyouroperatingsystem(OS)toopenaldquoportrdquotothecomputerusuallyport80WhenitworkstheOShandsbacktoyourprogramsomethingthatworkslikeafilebutisactuallysendingandreceivingbytesoverthenetworkwiresbetweenyourcomputerandtheothercomputerathttptestcomThisisalsothesamethingthathappenswithhttplocalhost8080butinthiscaseyoursquoretellingthebrowsertoconnecttoyourowncomputer(localhost)anduseport8080ratherthanthedefaultof80Youcouldalsodohttptestcom80andgetthesameresultexceptyoursquoreexplicitlysayingtouseport80insteadoflettingitbethatbydefault

RequestYourbrowserisconnectedusingtheaddressyougaveNowitneedstoaskfortheresourceitwants(oryouwant)ontheremoteserverIfyougavebookattheendoftheURLthenyouwantthefile(resource)atbookandmostserverswillusetherealfilebookindexhtmlbutpretenditdoesnrsquotexistWhatthebrowserdoestogetthisresourceissendarequesttotheserverIwonrsquotgetintoexactlyhowitdoesthisbutjustunderstandthatithastosendsomethingtoquerytheserverfortherequestTheinterestingthingisthattheseldquoresourcesrdquodonrsquothavetobefilesForinstancewhenthebrowserinyourapplicationasksforsomethingtheserverisreturningsomethingyourPythoncodegenerated

ServerTheserveristhecomputerattheendofabrowserrsquosconnectionthatknowshowtoansweryourbrowserrsquosrequestsforfilesresourcesMostwebserversjustsendfilesandthatrsquosactuallythemajorityoftrafficButyoursquoreactuallybuildingaserverinPythonthatknowshowtotakerequestsforresourcesandthenreturnstringsthatyoucraftusingPythonWhenyoudothiscraftingyouarepretendingtobeafiletothebrowserbutreallyitrsquosjustcodeAsyoucanseefromExercise50italsodoesnrsquottakemuchcodetocreatearesponse

ResponseThisistheHTML(CSSJavaScriptorimages)yourserverwantstosendbacktothebrowserastheanswertothebrowserrsquosrequestInthecaseoffilesitjustreadsthemoffthediskandsendsthemtothebrowserbutitwrapsthecontentsofthediskinaspecialldquoheaderrdquosothebrowserknowswhatitrsquosgettingInthecaseofyourapplicationyoursquorestillsendingthesamethingincludingtheheaderbutyougeneratethatdataontheflywithyourPythoncode

ThatisthefastestcrashcourseinhowawebbrowseraccessesinformationonserversontheinternetItshouldworkwellenoughforyoutounderstandthisexercisebutifnotreadaboutitasmuchasyoucanuntilyougetitAreallygoodwaytodothatistotakethediagramandbreakdifferentpartsofthewebapplicationyoudidinExercise50Ifyoucanbreakyourwebapplicationinpredictablewaysusingthediagramyoursquollstarttounderstandhowitworks

HowFormsWorkThebestwaytoplaywithformsistowritesomecodethatacceptsformdataandthenseewhatyoucandoTakeyourapppyfileandmakeitlooklikethis

Clickheretoviewcodeimage

form_testpy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hello)

8defindex()

9name=requestargsget(nameNobody)

10

11ifname

12greeting=fHelloname

13else

14greeting=HelloWorld

15

16returnrender_template(indexhtmlgreeting=greeting)

17

18if__name__==__main__

19apprun()Restartit(hitCTRL-Candthenrunitagain)to

makesureitloadsagainthenwithyourbrowsergoto

httplocalhost5000hellowhichshoulddisplayldquoIjustwantedto

sayHelloNobodyrdquoNextchangetheURLinyourbrowserto

httplocalhost5000helloname=Frankandyoursquollseeitsay

ldquoHelloFrankrdquoFinallychangethename=Frankparttobeyourname

Nowitrsquossayinghellotoyou

LetrsquosbreakdownthechangesImadetoyourscript1InsteadofjustastringforgreetingIrsquomnowusingrequestargstogetdatafromthebrowserThisisasimpledictthatcontainstheformvaluesaskey=valuepairs

2Ithenconstructthegreetingfromthenewnamewhichshouldbeveryfamiliartoyoubynow

3EverythingelseaboutthefileisthesameasbeforeYoursquorealsonotrestrictedtojustoneparameterontheURLChangethisexampletogivetwovariableslikethishttplocalhost5000helloname=Frankampgreet=HolaThenchangethecodetogetnameandgreetlikethisClickheretoviewcodeimage

greet=requestargsget(greetHello)

greeting=fgreetname

greeting=fgreetname

YoushouldalsotrynotgivingthegreetandnameparametersontheURLYoursquollsimplysendyourbrowsertohttplocalhost5000hellotoseethattheindexnowdefaultstoldquoNobodyrdquofornameandldquoHellordquoforgreet

CreatingHTMLFormsPassingtheparametersontheURLworksbutitrsquoskindofuglyandnoteasytouseforregularpeopleWhatyoureallywantisaldquoPOSTformrdquowhichisaspecialHTMLfilethathasaltformgttaginitThisformwillcollectinformationfromtheuserthensendittoyourwebapplicationjustlikeyoudidaboveLetrsquosmakeaquickonesoyoucanseehowitworksHerersquosthenewHTMLfileyouneedtocreateintemplateshello_formhtmlClickheretoviewcodeimage

hello_formhtml

lthtmlgt

ltheadgt

lttitlegtSampleWebFormlttitlegt

ltheadgt

ltbodygt

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

ltbodygt

lthtmlgtYoushouldthenchangeapppytolooklikethisClickhere

toviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hellomethods=[POSTGET])

8defindex()

9greeting=HelloWorld

10

11ifrequestmethod==POST

12name=requestform[name]

13greet=requestform[greet]

14greeting=fgreetname

15returnrender_template(indexhtmlgreeting=greeting)

16else

17returnrender_template(hello_formhtml)

18

19

20if__name__==__main__

21apprun()Onceyoursquovegotthosewrittenupsimplyrestart

thewebapplicationagainandhititwithyourbrowserlikebefore

ThistimeyoursquollgetaformaskingyouforldquoAGreetingrdquoandldquoYourNamerdquoWhenyouhittheSubmitbuttonontheformitwillgiveyouthesamegreetingyounormallygetbutthistimelookattheURLinyourbrowserSeehowitrsquoshttplocalhost5000helloeventhoughyousentinparametersThepartofthehello_formhtmlfilethatmakesthisworkisthelinewithltformaction=hellomethod=POSTgtThistellsyourbrowserto1Collectdatafromtheuserusingtheformfieldsinsidetheform

2SendthemtotheserverusingaPOSTtypeofrequestwhichisjustanotherbrowserrequestthatldquohidesrdquotheformfields

3SendthattothehelloURL(asshownintheaction=hellopart)

YoucanthenseehowthetwoltinputgttagsmatchthenamesofthevariablesinyournewcodeAlsonoticethatinsteadofjustaGETmethodinsideclassindexIhaveanothermethodPOSTHowthisnewapplicationworksisasfollows1Yourrequestgoestoindex()likenormalexceptnowthereisanif-statementthatcheckstherequestmethodforeitherPOSTorGETmethodsThisishowthebrowsertellsapppythatarequestiseitheraformsubmissionorURLparameters

2IfrequestmethodisPOSTthenyouprocesstheformasifitwerefilledoutandsubmittedreturningthepropergreeting

3Ifrequestmethodisanythingelsethenyousimplyreturnthehello_formhtmlfortheusertofillout

AsanexercisegointothetemplatesindexhtmlfileandaddalinkbacktojusthellosothatyoucankeepfillingouttheformandseeingtheresultsMakesureyoucanexplainhowthislinkworksandhowitrsquoslettingyoucyclebetweentemplatesindexhtmlandtemplateshello_formhtmlandwhatrsquosbeingruninsidethislatestPythoncode

CreatingaLayoutTemplateWhenyouworkonyourgameinthenextexerciseyoursquollneedtomakeabunchoflittleHTMLpagesWritingafullwebpageeachtimewillquicklybecometediousLuckilyyoucancreatealdquolayoutrdquotemplateorakindofshellthatwillwrapallyourotherpageswithcommonheadersandfootersGoodprogrammerstrytoreducerepetitionsolayoutsareessentialforbeingagoodprogrammerChangetemplatesindexhtmltobelikethisClickheretoviewcodeimage

index_laid_outhtml

extendslayouthtml

blockcontent

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

endblock

Thenchangetemplateshello_formhtmltobelikethisClickheretoviewcodeimage

hello_form_laid_outhtml

extendslayouthtml

blockcontent

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

endblock

AllwersquoredoingisstrippingouttheldquoboilerplaterdquoatthetopandthebottomwhichisalwaysoneverypageWersquollputthatbackintoasingletemplateslayouthtmlfilethathandlesitforusfromnowonOnceyouhavethosechangescreateatemplateslayouthtmlfilewiththisinitClickheretoviewcodeimage

layouthtml

lthtmlgt

ltheadgt

lttitlegtGothonsFromPlanetPercal25lttitlegt

ltheadgt

ltbodygt

blockcontent

endblock

ltbodygt

lthtmlgtThisfilelookslikearegulartemplateexceptthatitrsquos

goingtobepassedthecontentsoftheothertemplatesandusedto

wrapthemAnythingyouputinheredoesnrsquotneedtobeintheother

templatesYourotherHTMLtemplateswillbeinsertedintothe

blockcontentsectionflaskknowstousethislayouthtmlasthe

layoutbecauseyouputextendslayouthtmlatthetopofyour

templates

WritingAutomatedTestsforFormsItrsquoseasytotestawebapplicationwithyourbrowserbyjusthittingrefreshbutcomeonwersquoreprogrammershereWhydosomerepetitivetaskwhenwecanwritesomecodetotestourapplicationWhatyoursquoregoingtodonextiswritealittletestforyourwebapplicationformbasedonwhatyoulearnedinExercise

47IfyoudonrsquotrememberExercise47readitagainCreateanewfilenamedtestsapp_testspywiththisClickheretoviewcodeimage

app_testspy

1fromnosetoolsimport

2fromappimportapp

3

4appconfig[TESTING]=True

5web=apptest_client()

6

7deftest_index()

8rv=webget(follow_redirects=True)

9assert_equal(rvstatus_code404)

10

11rv=webget(hellofollow_redirects=True)

12assert_equal(rvstatus_code200)

13assert_in(bFillOutThisFormrvdata)

14

15data=nameZedgreetHola

16rv=webpost(hellofollow_redirects=Truedata=data)

17assert_in(bZedrvdata)

18assert_in(bHolarvdata)Finallyusenoseteststorun

thistestsetupandtestyourwebapplication$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0059s

OK

WhatIrsquomdoinghereisIrsquomactuallyimportingthewholeapplicationfromtheapppymodulethenrunningitmanuallyTheflaskframeworkhasaverysimpleAPIforprocessingrequestswhichlookslikethisClickheretoviewcodeimage

data=nameZedgreetHola

rv=webpost(hellofollow_redirects=Truedata=data)Thismeans

youcansendaPOSTrequestusingthepost()methodandthengiveit

theformdataasadictEverythingelseworksthesameastesting

webget()requests

Inthetestsapp_testspyautomatedtestIrsquomfirstmakingsuretheURLreturnsaldquo404NotFoundrdquoresponsesinceitactuallydoesnrsquotexistThenIrsquomcheckingthathelloworkswithbothaGETandaPOSTformFollowing

thetestshouldbefairlysimpleevenifyoumightnottotallyknowwhatrsquosgoingonTakesometimestudyingthislatestapplicationespeciallyhowtheautomatedtestingworksMakesureyouunderstandhowIimportedtheapplicationfromapppyandranitdirectlyfortheautomatedtestThisisanimportanttrickthatwillleadtomorelearning

StudyDrills1ReadevenmoreaboutHTMLandgivethesimpleformabetterlayoutIthelpstodrawwhatyouwanttodoonpaperandthenimplementitwithHTML

2Thisoneishardbuttrytofigureouthowyoursquoddoafileuploadformsothatyoucanuploadanimageandsaveittothedisk

3Thisisevenmoremind-numbingbutgofindtheHTTPRFC(whichisthedocumentthatdescribeshowHTTPworks)andreadasmuchofitasyoucanItisreallyboringbutcomesinhandyonceinawhile

4ThiswillalsobereallydifficultbutseeifyoucanfindsomeonetohelpyousetupawebserverlikeApacheNginxorthttpdTrytoserveacoupleofyourhtmlandcssfileswithitjusttoseeifyoucanDonrsquotworryifyoucanrsquotWebserverskindofsuck

5Takeabreakafterthisandjusttrymakingasmanydifferentwebapplicationsasyoucan

BreakingItThisisagreatplacetofigureouthowtobreakwebapplicationsYoushouldexperimentwiththefollowing

1HowmuchdamagecanyoudowiththeFLASK_DEBUGsettingonBecarefulthatyoudonrsquotwipeyourselfoutdoingthis

2LetrsquossayyoudonrsquothavedefaultparametersfortheformsWhatcouldgowrong

3YoursquorecheckingforPOSTandthenldquoanythingelserdquoYoucanusethecurlcommandlinetooltogeneratedifferentrequesttypesWhathappens

Exercise52TheStartofYourWebGame

WersquorecomingtotheendofthebookandinthisexerciseIrsquomgoingtoreallychallengeyouWhenyoursquoredoneyoursquollbeareasonablycompetentPythonbeginnerYoursquollstillneedtogothroughafewmorebooksandwriteacouplemoreprojectsbutyoursquollhavetheskillstocompletethemTheonlyobstacleswillbetimemotivationandresourcesInthisexercisewewonrsquotmakeacompletegamebutinsteadwersquollmakeanldquoenginerdquothatcanrunthegamefromExercise47inthebrowserThiswillinvolverefactoringExercise43mixinginthestructurefromExercise47addingautomatedtestsandfinallycreatingawebenginethatcanrunthegamesThisexercisewillbehugeandIpredictyoucouldspendanywherefromaweektomonthsonitbeforemovingonItrsquosbesttoattackitinlittlechunksanddoabitanighttakingyourtimetomakeeverythingworkbeforemovingon

RefactoringtheExercise43GameYoursquovebeenalteringthegothonwebprojectfortwoexercisesandyoursquolldoitonemoretimeinthisexerciseTheskillyoursquorelearningiscalledldquorefactoringrdquoorasIliketocallitldquofixingstuffrdquoRefactoringisatermprogrammersusetodescribetheprocessoftakingoldcodeandchangingittohavenewfeaturesorjusttocleanitupYoursquovebeendoingthiswithoutevenknowingitasitrsquossecondnaturetobuildingsoftwareWhatyoursquolldointhispartistaketheideasfromExercise47ofatestableldquomaprdquoofRoomsandthegamefromExercise43andcombinethemtogethertocreateanewgamestructureItwillhavethesamecontentjustldquorefactoredrdquotohaveabetterstructureThefirststepistograbthecodefromex47gamepycopyittogothonwebplanispherepycopythetestsex47_testspyfiletotestsplanisphere_testspyandrunnosetestsagaintomakesureitkeepsworkingThewordldquoplanisphererdquoisjustasynonymforldquomaprdquowhichavoidsPythonrsquosbuilt-inmapfunctionThethesaurusisyourfriend

WarningFromnowonIwonrsquotshowyoutheoutputofatestrunJustassumethatyoushouldbedoingitanditrsquolllookliketheprecedingunlessyouhaveanerror

OnceyouhavethecodefromExercise47copiedoveritrsquostimetorefactorittohavetheExercise43mapinitIrsquomgoingtostartoffbylayingdownthebasicstructureandthenyoursquollhaveanassignmenttomaketheplanispherepyfileandtheplanisphere_testspyfilecompleteLayoutthebasicstructureofthemapusingtheRoomclassasitisnowClickheretoviewcodeimage

planispherepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)

13

14

15central_corridor=Room(CentralCorridor

16

17TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyed

18yourentirecrewYouarethelastsurvivingmemberandyour

last

19missionistogettheneutrondestructbombfromtheWeapons

Armoryput

20itinthebridgeandblowtheshipupaftergettingintoan

escapepod

21

22YourerunningdownthecentralcorridortotheWeaponsArmory

whena

23Gothonjumpsoutredscalyskindarkgrimyteethandevil

clown

24costumeflowingaroundhishatefilledbodyHesblocking

thedoorto

25theArmoryandabouttopullaweapontoblastyou

26)

27

28

29laser_weapon_armory=Room(LaserWeaponArmory

30

31LuckyforyoutheymadeyoulearnGothoninsultsinthe

academyYou

32telltheoneGothonjokeyouknowLbhezbgurevffbsngjura

furfvgf

33nebhaqgurubhfrfurfvgfnebhaqgurubhfrTheGothon

stopstries

34nottolaughthenbustsoutlaughingandcantmoveWhile

hes

35laughingyourunupandshoothimsquareintheheadputting

himdown

36thenjumpthroughtheWeaponArmorydoor

37

38YoudoadiverollintotheWeaponArmorycrouchandscanthe

roomfor

39moreGothonsthatmightbehidingItsdeadquiettoo

quietYou

40standupandruntothefarsideoftheroomandfindthe

neutronbomb

41initscontainerTheresakeypadlockontheboxandyou

needthe

42codetogetthebomboutIfyougetthecodewrong10times

thenthe

43lockclosesforeverandyoucantgetthebombThecodeis3

digits

44)

45

46

47the_bridge=Room(TheBridge

48

49Thecontainerclicksopenandthesealbreakslettinggas

outYou

50grabtheneutronbombandrunasfastasyoucantothebridge

whereyou

51mustplaceitintherightspot

52

53YouburstontotheBridgewiththenetrondestructbombunder

yourarm

54andsurprise5Gothonswhoaretryingtotakecontrolofthe

shipEach

55ofthemhasanevenuglierclowncostumethanthelastThey

havent

56pulledtheirweaponsoutyetastheyseetheactivebomb

underyourarm

57anddontwanttosetitoff

58)

59

60

61escape_pod=Room(EscapePod

62

63Youpointyourblasteratthebombunderyourarmandthe

Gothonsput

64theirhandsupandstarttosweatYouinchbackwardtothe

dooropen

65itandthencarefullyplacethebombonthefloorpointing

your

66blasteratitYouthenjumpbackthroughthedoorpunchthe

close

67buttonandblastthelocksotheGothonscantgetoutNow

thatthe

68bombisplacedyouruntotheescapepodtogetoffthistin

can

69

70Yourushthroughtheshipdesperatelytryingtomakeittothe

escape

71podbeforethewholeshipexplodesItseemslikehardlyany

Gothons

72areontheshipsoyourrunisclearofinterferenceYou

gettothe

73chamberwiththeescapepodsandnowneedtopickoneto

takeSomeof

74themcouldbedamagedbutyoudonthavetimeto

lookTheres5pods

75whichonedoyoutake

76)

77

78

79the_end_winner=Room(TheEnd

80

81Youjumpintopod2andhittheejectbuttonThepodeasily

slidesout

82intospaceheadingtotheplanetbelowAsitfliestothe

planetyou

83lookbackandseeyourshipimplodethenexplodelikeabright

star

84takingouttheGothonshipatthesametimeYouwon

85)

86

87

88the_end_loser=Room(TheEnd

89

90YoujumpintoarandompodandhittheejectbuttonThepod

escapes

91outintothevoidofspacethenimplodesasthehull

rupturescrushing

92yourbodyintojamjelly

93

94)

95

96escape_podadd_paths(

972the_end_winner

98the_end_loser

99)

100

101generic_death=Room(deathYoudied)

102

103the_bridgeadd_paths(

104throwthebombgeneric_death

105slowlyplacethebombescape_pod

106)

107

108laser_weapon_armoryadd_paths(

1090132the_bridge

110generic_death

111)

112

113central_corridoradd_paths(

114shootgeneric_death

115dodgegeneric_death

116tellajokelaser_weapon_armory

117)

118

119START=central_corridor

120

121defload_room(name)

122

123Thereisapotentialsecurityproblemhere

124WhogetstosetnameCanthatexposeavariable

125

126returnglobals()get(name)

127

128defname_room(room)

129

130SamepossiblesecurityproblemCanyoutrustroom

131Whatsabettersolutionthanthisglobalslookup

132

133forkeyvalueinglobals()items()

134ifvalue==room

135returnkeyYoursquollnoticethatthereareacouple

ofproblemswithourRoomclassandthismap1Wehavetoputthe

textthatwasintheif-elseclausesthatgotprintedbeforeentering

aroomaspartofeachroomThismeansyoucanrsquotshufflethe

planispherearoundwhichwouldbeniceYoursquollbefixingthatupin

thisexercise

2TherearepartsintheoriginalgamewherewerancodethatdeterminedthingslikethebombrsquoskeypadcodeortherightpodInthisgamewejustpicksomedefaultsandgowithitbutlateryoursquollbegivenStudyDrillstomakethisworkagain

3Irsquovejustmadeageneric_deathendingforallofthebaddecisionswhichyoursquollhavetofinishformeYoursquollneedtogobackthroughandaddinalltheoriginalendingsandmakesuretheywork

4Irsquovegotanewkindoftransitionlabeledthatwillbeusedforaldquocatch-allrdquoactionintheengine

Onceyoursquovegotthatbasicallywrittenoutherersquosthenewautomatedtesttestsplanisphere_testpythatyoushouldhavetogetyourselfstartedClickheretoviewcodeimage

planisphere_testspy

1fromnosetoolsimport

2fromgothonwebplanisphereimport

3

4deftest_room()

5gold=Room(GoldRoom

6Thisroomhasgoldinityoucangrab

Theresa

7doortothenorth)

8assert_equal(goldnameGoldRoom)

9assert_equal(goldpaths)

10

11deftest_room_paths()

12center=Room(CenterTestroominthecenter)

13north=Room(NorthTestroominthenorth)

14south=Room(SouthTestroominthesouth)

15

16centeradd_paths(northnorthsouthsouth)

17assert_equal(centergo(north)north)

18assert_equal(centergo(south)south)

19

20deftest_map()

21start=Room(StartYoucangowestanddownahole)

22west=Room(TreesTherearetreeshereyoucango

east)

23down=Room(DungeonItsdarkdownhereyoucango

up)

24

25startadd_paths(westwestdowndown)

26westadd_paths(eaststart)

27downadd_paths(upstart)

28

29assert_equal(startgo(west)west)

30assert_equal(startgo(west)go(east)start)

31assert_equal(startgo(down)go(up)start)

32

33deftest_gothon_game_map()

34start_room=load_room(START)

35assert_equal(start_roomgo(shoot)generic_death)

36assert_equal(start_roomgo(dodge)generic_death)

37

38room=start_roomgo(tellajoke)

39assert_equal(roomlaser_weapon_armory)Yourtaskinthis

partoftheexerciseistocompletethemapandmaketheautomated

testcompletelyvalidatethewholemapThisincludesfixingallthe

generic_deathobjectstoberealendingsMakesurethisworksreally

wellandthatyourtestisascompleteaspossiblebecausewersquollbe

changingthismaplaterandyoursquollusetheteststomakesureit

keepsworking

CreatinganEngineYoushouldhaveyourgamemapworkingandagoodunittestforitInowwantyoutomakeasimplelittlegameenginethatwillruntheroomscollectinputfromtheplayerandkeeptrackofwhereaplayerisinthegameWersquollbeusingthesessionsyoujustlearnedtomakeasimplegameenginethatwilldothefollowing

1Startanewgamefornewusers2Presenttheroomtotheuser3Takeinputfromtheuser4Runuserinputthroughthegame5Displaytheresultsandkeepgoinguntiltheuserdies

Todothisyoursquoregoingtotakethetrustyapppyyoursquovebeenhackingonandcreateafullyworkingsession-basedgameengineThecatchisIrsquomgoingtomakeaverysimpleonewithbasicHTMLfilesanditrsquollbeuptoyoutocompleteitHerersquosthebaseengineClickheretoviewcodeimage

apppy

1fromflaskimportFlasksessionredirecturl_forescape

request

2fromflaskimportrender_template

3fromgothonwebimportplanisphere

4

5app=Flask(__name__)

6

7approute()

8defindex()

9thisisusedtosetupthesessionwithstartingvalues

10session[room_name]=planisphereSTART

11returnredirect(url_for(game))

12

13approute(gamemethods=[GETPOST])

14defgame()

15room_name=sessionget(room_name)

16

17ifrequestmethod==GET

18ifroom_name

19room=planisphereload_room(room_name)

20returnrender_template(show_roomhtmlroom=room)

21else

22whyisthereheredoyouneedit

23returnrender_template(you_diedhtml)

24else

25action=requestformget(action)

26

27ifroom_nameandaction

28room=planisphereload_room(room_name)

29next_room=roomgo(action)

30

31ifnotnext_room

32session[room_name]=

planispherename_room(room)

33else

34session[room_name]=

planispherename_room(next_room)

35

36returnredirect(url_for(game))

37

38

39YOUSHOULDCHANGETHISIFYOUPUTONTHEINTERNET

40appsecret_key=A0Zr98j3yXR~XHHjmN]LWXRT

41

42if__name__==__main__

43apprun()Thereareevenmorenewthingsinthisscript

butamazinglyitrsquosanentireweb-basedgameengineinasmallfile

BeforeyourunapppyyouneedtochangeyourPYTHONPATHenvironment

variableDonrsquotknowwhatthatisIknowitrsquoskindofdumbbutyou

havetolearnwhatthisistorunevenbasicPythonprogramsthatrsquos

howPythonpeoplelikethings

InyourTerminaltypeClickheretoviewcodeimageexportPYTHONPATH=$PYTHONPATH

OnWindowsPowerShelldoClickheretoviewcodeimage$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

YoushouldonlyhavetodoitoncepershellsessionbutifyougetanimporterrorthenyouprobablyneedtodothisoryoudiditwrongYoushouldnextdeletetemplateshello_formhtmlandtemplatesindexhtmlandcreatethetwotemplatesmentionedintheprecedingcodeHerersquosaverysimpletemplatesshow_roomhtmlClickheretoviewcodeimage

show_roomhtml

extendslayouthtml

blockcontent

lth1gtroomnamelth1gt

ltpregt

roomdescription

ltpregt

ifroomnamein[deathTheEnd]

ltpgtltahref=gtPlayAgainltagtltpgt

else

ltpgt

ltformaction=gamemethod=POSTgt

-ltinputtype=textname=actiongtltinputtype=SUBMITgt

ltformgt

ltpgt

endif

endblock

ThatisthetemplatetoshowaroomasyoutravelthroughthegameNextyouneedonetotellsomeonetheydiedinthecasethattheygottotheendofthemaponaccidentwhichistemplatesyou_diedhtmlClickheretoviewcodeimage

you_diedhtml

lth1gtYouDiedlth1gt

ltpgtLookslikeyoubitthedustltpgt

ltpgtltahref=gtPlayAgainltagtltpgtWiththoseinplaceyoushouldnow

beabletodothefollowing1Getthetesttestsapp_testspy

workingagainsothatyouaretestingthegameYouwonrsquotbeableto

domuchmorethanafewclicksinthegamebecauseofsessionsbut

youshouldbeabletodosomebasics

2Runthepython36apppyscriptandtestoutthegameYoushouldbeabletorefreshandfixthegamelikenormalYoushouldalsobeabletoworkwiththegameHTMLandengineuntilitdoesallthethingsyouwantittodo

YourFinalExamDoyoufeellikethiswasahugeamountofinformationthrownatyouallatonceGoodIwantyoutohavesomethingtotinkerwithwhileyoubuildyourskillsTocompletethisexerciseIrsquomgoingtogiveyouafinalsetoftasksforyoutocompleteonyourownYoursquollnoticethatwhatyoursquovewrittensofarisnrsquotverywellbuiltitisjustafirstversionofthecodeYourjobnowistomakethegamemorecompletebydoingthesethings

1FixallthebugsImentioninthecodeandanythatIdidnrsquotmentionIfyoufindnewbugsletmeknow

2Improvealloftheautomatedtestssothatyoutestmoreoftheapplicationandgettoapointwhereyouuseatestratherthanyourbrowsertochecktheapplicationwhileyouwork

3MaketheHTMLlookbetter4Researchloginsandcreateasignupsystemfortheapplicationsopeoplecanhaveloginsandhighscores

5Completethegamemapmakingitaslargeandfeature-completeaspossible

6Givepeoplealdquohelprdquosystemthatletsthemaskwhattheycandoateachroominthegame

7Addanyotherfeaturesyoucanthinkoftothegame8CreateseveralldquomapsrdquoandletpeoplechooseagametheywanttorunYourapppyengineshouldbeabletorunanymapofroomsyougiveitsoyoucansupportmultiplegames

9FinallyusewhatyoulearnedinExercises48and49tocreateabetterinputprocessorYouhavemostofthecodenecessaryyoujustneedtoimprovethegrammarandhookituptoyourinputformandtheGameEngine

Goodluck

Goodluck

CommonStudentQuestionsIrsquomusingsessionsinmygameandIcanrsquottestitwithnosetestsReadtheFlaskTestingDocumentationaboutldquoOtherTestingTricksrdquo(httpflaskpocooorgdocs012testingother-testing-tricks)forinformationoncreatingfakesessionsinsideyourtests

IgetanImportErrorItcouldbeoneormoreofthesewrongdirectorywrongPythonversionPYTHONPATHnotsetno__init__pyfileandorspellingmistakeinimport

NextSteps

YoursquorenotaprogrammerquiteyetIliketothinkofthisbookasgivingyouyourldquoprogrammingblackbeltrdquoYouknowenoughtostartanotherbookonprogrammingandhandleitjustfineThisbookshouldhavegivenyouthementaltoolsandattitudeyouneedtogothroughmostPythonbooksandactuallylearnsomethingItmightevenmakeiteasyIrecommendyoucheckoutsomeoftheseprojectsandtrytobuildsomethingwiththem

bullLearnRubyTheHardWay(httpslearnrubythehardwayorg)YouwilllearnevenmoreaboutprogrammingasyoulearnmoreprogramminglanguagessotrylearningRubytoo

bullTheDjangoTutorial(httpsdocsdjangoprojectcomen111intro)BuildawebapplicationwiththeDjangowebframework

bullSciPy(httpswwwscipyorg)Checkthisoutifyoursquoreintosciencemathandengineering

bullPyGame(httpwwwpygameorg)MakeagamewithgraphicsandsoundbullPandas(httppandaspydataorg)Usethisfordoingdatamanipulationandanalysis

bullNaturalLanguageToolkit(httpwwwnltkorg)Usethisforanalyzingwrittentextandwritingthingslikespamfiltersandchatbots

bullTensorFlow(httpswwwtensorfloworg)Usethisformachinelearningandvisualization

bullRequests(httpdocspython-requestsorg)LearntheclientsideofHTTPandtheweb

bullScraPy(httpsscrapyorg)Tryscrapingsomewebsitestogetinformationoffthem

bullKivy(httpskivyorg)Createuserinterfacesondesktopsandmobileplatforms

bullLearnCTheHardWay(httpslearncodethehardwayorg)AfteryoursquorefamiliarwithPythontrylearningCandalgorithmswithmyotherbookTakeitslowCisdifferentbutaverygoodthingtolearn

PickoneoftheprecedingresourcesandgothroughanytutorialsanddocumentationtheyhaveAsyougothroughdocumentationwithcodeinittype

inallofthecodeandmakeitworkThatrsquoshowIdoitThatrsquoshoweveryprogrammerdoesitReadingprogrammingdocumentationisnotenoughtolearnityouhavetodoitAfteryougetthroughthetutorialandanyotherdocumentationtheyhavemakesomethingAnythingwilldoevensomethingsomeoneelsehasalreadywrittenJustmakesomethingJustunderstandanythingyouwritewillprobablysuckThatrsquosalrightthoughIsuckateveryprogramminglanguageatfirstNobodywritespureperfectgoldwhentheyrsquoreabeginnerandanyonewhotellsyoutheydidisahugeliar

HowtoLearnAnyProgrammingLanguageIrsquomgoingtoteachyouhowtolearnmostoftheprogramminglanguagesyoumaywanttolearninthefutureTheorganizationofthisbookisbasedonhowIandmanyotherprogrammerslearnnewlanguagesTheprocessthatIusuallyfollowisasfollows

1Getabookorsomeintroductorytextaboutthelanguage2Gothroughthebookandtypeinallofthecodemakingallofitrun3Readthebookasyouworkonthecodetakingnotes4Usethelanguagetoimplementasmallsetofprogramsyouarefamiliarwithinanotherlanguage

5ReadotherpeoplersquoscodeinthelanguageandtrytocopytheirpatternsInthisbookIforcedyoutogothroughthisprocessveryslowlyandinsmallchunksOtherbooksarenrsquotorganizedthesamewayandthismeansyouhavetoextrapolatehowIrsquovemadeyoudothistohowtheircontentisorganizedThebestwaytodothisistoreadthebooklightlyandmakealistofallthemajorcodesectionsTurnthislistintoasetofexercisesbasedonthechaptersandthensimplydotheminorderoneatatimeTheprecedingprocessalsoworksfornewtechnologiesassumingtheyhavebooksyoucanreadForanythingwithoutbooksyoudotheaboveprocessbutuseonlinedocumentationorsourcecodeasyourinitialintroductionEachnewlanguageyoulearnmakesyouabetterprogrammerandasyoulearnmorelanguagestheybecomeeasiertolearnByyourthirdorfourthlanguageyoushouldbeabletopickupsimilarlanguagesinaweekwithstrangerlanguagestakinglongerNowthatyouknowPythonyoucouldpotentiallylearnRubyandJavaScriptfairlyquicklybycomparisonThisissimplybecausemanylanguagessharesimilarconceptsandonceyoulearntheconceptsinonelanguagetheyworkinothersThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbea

ThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbeastupidtouristAstupidtouristissomeonewhogoestoanothercountryandthencomplainsthatthefoodisnrsquotlikethefoodathome(ldquoWhycanrsquotIgetagoodburgerinthisstupidcountryrdquo)WhenyoursquorelearninganewlanguageassumethatwhatitdoesisnrsquotstupiditrsquosjustdifferentandembraceitsoyoucanlearnitAfteryoulearnalanguagethoughdonrsquotbeaslavetothatlanguagersquoswayofdoingthingsSometimesthepeoplewhousealanguageactuallydosomeveryidioticthingsfornootherreasonthanldquothatrsquoshowwersquovealwaysdoneitrdquoIfyoulikeyourstylebetterandyouknowhoweveryoneelsedoesitthenfeelfreetobreaktheirrulesifitimprovesthingsIreallyenjoylearningnewprogramminglanguagesIthinkofmyselfasaldquoprogrammeranthropologistrdquoandthinkoflanguagesaslittleinsightsaboutthegroupofprogrammerswhousethemIrsquomlearningalanguagetheyallusetotalktoeachotherthroughcomputersandIfindthisfascinatingThenagainIrsquomkindofaweirdguysojustlearnprogramminglanguagesbecauseyouwanttoEnjoyThisisreallyfunstuff

AdvicefromanOldProgrammer

YoursquovefinishedthisbookandhavedecidedtocontinuewithprogrammingMaybeitwillbeacareerforyouormaybeitwillbeahobbyYoursquollneedsomeadvicetomakesureyoucontinueontherightpathandgetthemostenjoymentoutofyournewlychosenactivityIrsquovebeenprogrammingforaverylongtimeSolongthatitrsquosincrediblyboringtomeAtthetimethatIwrotethisbookIknewabout20programminglanguagesandcouldlearnnewonesinaboutadaytoaweekdependingonhowweirdtheywereEventuallythoughthisjustbecameboringandcouldnrsquotholdmyinterestanymoreThisdoesnrsquotmeanIthinkprogrammingisboringorthatyouwillthinkitrsquosboringonlythatIfindituninterestingatthispointinmyjourneyWhatIdiscoveredafterthisjourneyoflearningisthatitrsquosnotthelanguagesthatmatterbutwhatyoudowiththemActuallyIalwaysknewthatbutIrsquodgetdistractedbythelanguagesandforgetitperiodicallyNowIneverforgetitandneithershouldyouWhichprogramminglanguageyoulearnandusedoesnrsquotmatterDonotgetsuckedintothereligionsurroundingprogramminglanguagesasthatwillonlyblindyoutotheirtruepurposeofbeingyourtoolfordoinginterestingthingsProgrammingasanintellectualactivityistheonlyartformthatallowsyoutocreateinteractiveartYoucancreateprojectsthatotherpeoplecanplaywithandyoucantalktothemindirectlyNootherartformisquitethisinteractiveMoviesflowtotheaudienceinonedirectionPaintingsdonotmoveCodegoesbothwaysProgrammingasaprofessionisonlymoderatelyinterestingItcanbeagoodjobbutyoucouldmakeaboutthesamemoneyandbehappierrunningafastfoodjointYoursquoremuchbetteroffusingcodeasyoursecretweaponinanotherprofessionPeoplewhocancodeintheworldoftechnologycompaniesareadimeadozenandgetnorespectPeoplewhocancodeinbiologymedicinegovernmentsociologyphysicshistoryandmathematicsarerespectedandcandoamazingthingstoadvancethosedisciplinesOfcourseallofthisadviceispointlessIfyoulikedlearningtowritesoftwarewiththisbookyoushouldtrytouseittoimproveyourlifeanywayyoucanGooutandexplorethisweirdwonderfulnewintellectualpursuitthatbarelyanyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhile

anyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhileyoucanFinallyIrsquollsaythatlearningtocreatesoftwarechangesyouandmakesyoudifferentNotbetterorworsejustdifferentYoumayfindthatpeopletreatyouharshlybecauseyoucancreatesoftwaremaybeusingwordslikeldquonerdrdquoMaybeyoursquollfindthatbecauseyoucandissecttheirlogictheyhatearguingwithyouYoumayevenfindthatsimplyknowinghowacomputerworksmakesyouannoyingandweirdtothemTothisIhavejustonepieceofadvicetheycangotohellTheworldneedsmoreweirdpeoplewhoknowhowthingsworkandwholovetofigureitalloutWhentheytreatyoulikethisjustrememberthatthisisyourjourneynottheirsBeingdifferentisnotacrimeandpeoplewhotellyouitisarejustjealousthatyoursquovepickedupaskilltheyneverintheirwildestdreamscouldacquireYoucancodeTheycannotThatisprettydamncool

AppendixCommandLineCrashCourse

ThisappendixisasuperfastcourseinusingthecommandlineItisintendedtobedonerapidlyinaboutadayortwoandnotmeanttoteachyouadvancedshellusage

IntroductionShutUpandShellThisappendixisacrashcourseinusingthecommandlinetomakeyourcomputerperformtasksAsacrashcourseitrsquosnotasdetailedorextensiveasmyotherbooksItissimplydesignedtogetyoubarelycapableenoughtostartusingyourcomputerlikearealprogrammerdoesWhenyoursquoredonewiththisappendixyouwillbeabletogivemostofthebasiccommandsthateveryshellusertoucheseverydayYoursquollunderstandthebasicsofdirectoriesandafewotherconceptsTheonlypieceofadviceIamgoingtogiveyouisthis

ShutupandtypeallofthisinSorrytobemeanbutthatrsquoswhatyouhavetodoIfyouhaveanirrationalfearofthecommandlinetheonlywaytoconqueranirrationalfearistojustshutupandfightthroughitYouarenotgoingtodestroyyourcomputerYouarenotgoingtobethrownintosomejailatthebottomofMicrosoftrsquosRedmondcampusYourfriendswonrsquotlaughatyouforbeinganerdSimplyignoreanystupidweirdreasonsyouhaveforfearingthecommandlineWhyBecauseifyouwanttolearntocodethenyoumustlearnthisProgramminglanguagesareadvancedwaystocontrolyourcomputerwithlanguageThecommandlineisthebabybrotherofprogramminglanguagesLearningthecommandlineteachesyoutocontrolthecomputerusinglanguageOnceyougetpastthatyoucanthenmoveontowritingcodeandfeelinglikeyouactuallyownthehunkofmetalyoujustbought

HowtoUseThisAppendixThebestwaytousethisappendixistodothefollowing

bullGetyourselfasmallpapernotebookandapenbullStartatthebeginningoftheappendixanddoeachexerciseexactlyasyoursquoretold

bullWhenyoureadsomethingthatdoesnrsquotmakesenseorthatyoudonrsquotunderstandwriteitdowninyournotebookLeavealittlespacesoyoucanwriteananswer

bullAfteryoufinishanexercisegobackthroughyournotebookandreviewthequestionsyouhaveTrytoanswerthembysearchingonlineandaskingfriendswhomightknowtheanswerEmailmeathelplearncodethehardwayorgandIrsquollhelpyoutoo

JustkeepgoingthroughthisprocessofdoinganexercisewritingdownquestionsyouhavethengoingbackthroughandansweringthequestionsyoucanBythetimeyoursquoredoneyoursquollactuallyknowalotmorethanyouthinkaboutusingthecommandline

YouWillBeMemorizingThingsIrsquomwarningyouaheadoftimethatIrsquomgoingtomakeyoumemorizethingsrightawayThisisthequickestwaytogetyoucapableatsomethingbutforsomepeoplememorizationispainfulJustfightthroughitanddoitanywayMemorizationisanimportantskillinlearningthingssoyoushouldgetoveryourfearofitHerersquoshowyoumemorizethings

bullTellyourselfyouwilldoitDonrsquottrytofindtricksoreasywaysoutofitjustsitdownanddoit

bullWritewhatyouwanttomemorizeonsomeindexcardsPutonehalfofwhatyouneedtolearnononesidethenanotherhalfontheotherside

bullEverydayforabout15to30minutesdrillyourselfontheindexcardstryingtorecalleachonePutanycardsyoudonrsquotgetrightintoadifferentpilejustdrillthosecardsuntilyougetboredthentrythewholedeckandseeifyouimprove

bullBeforeyougotobeddrilljustthecardsyougotwrongforabout5minutesthengotosleep

ThereareothertechniqueslikeyoucanwritewhatyouneedtolearnonasheetofpaperlaminateitthenstickittothewallofyourshowerWhileyoursquorebathingdrilltheknowledgewithoutlookingandwhenyougetstuckglanceatittorefreshyourmemoryIfyoudothiseverydayyoushouldbeabletomemorizemostthingsItellyoutomemorizeinaboutaweektoamonthOnceyoudonearlyeverythingelsebecomeseasierandintuitivewhichisthepurposeofmemorizationItrsquosnottoteachyouabstractconceptsbutrathertoingrainthebasicssothattheyareintuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthese

intuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthesebasicstheystopbeingspeedbumpspreventingyoufromlearningmoreadvancedabstractconcepts

TheSetupInthisappendixyouwillbeinstructedtodothreethings

bullDosomethingsinyourshell(commandlineTerminalPowerShell)bullLearnaboutwhatyoujustdidbullDomoreonyourown

ForthisfirstexerciseyoursquollbeexpectedtogetyourTerminalopenandworkingsothatyoucandotherestoftheappendix

DoThisGetyourTerminalshellorPowerShellworkingsoyoucanaccessitquicklyandknowthatitworksmacOS

FormacOSyoursquollneedtodothisbullHolddownthecommandkeyandhitthespacebarbullAsearchbarwillpopupbullTypeTerminalbullClickontheTerminalapplicationthatlookskindoflikeablackboxbullThiswillopenTerminalbullYoucannowgotoyourdockandCTRL-clicktopullupthemenuthenselectOptionsrarrKeepIndock

NowyouhaveyourTerminalopenanditrsquosinyourdocksoyoucangettoitLinux

IrsquomassumingthatifyouhaveLinuxthenyoualreadyknowhowtogetatyourTerminalLookthroughthemenuforyourwindowmanagerforanythingnamedldquoShellrdquoorldquoTerminalrdquoWindows

OnWindowswersquoregoingtousePowerShellPeopleusedtoworkwithaprogramcalledcmdexebutitrsquosnotnearlyasusableasPowerShellIfyouhaveWindows7orlaterdothis

bullClickStartbullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquo

bullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquobullHitEnter

IfyoudonrsquothaveWindows7youshouldseriouslyconsiderupgradingIfyoustillinsistonnotupgradingthenyoucantryinstallingPowerShellfromMicrosoftrsquosdownloadcenterSearchonlinetofindldquopowershelldownloadsrdquoforyourversionofWindowsYouareonyourownthoughsinceIdonrsquothaveWindowsXPbuthopefullythePowerShellexperienceisthesame

YouLearnedThisYoulearnedhowtogetyourTerminalopensoyoucandotherestofthisappendix

WarningIfyouhavethatreallysmartfriendwhoalreadyknowsLinuxignoreherwhenshetellsyoutousesomethingotherthanBashIrsquomteachingyouBashThatrsquositShewillclaimthatzshwillgiveyou30moreIQpointsandwinyoumillionsinthestockmarketIgnoreherYourgoalistogetcapableenoughandatthislevelitdoesnrsquotmatterwhichshellyouuseThenextwarningisstayoffIRCorotherplaceswhereldquohackersrdquohangoutTheythinkitrsquosfunnytohandyoucommandsthatcandestroyyourcomputerThecommandrm-rfisaclassicthatyoumustnevertypeJustavoidthemIfyouneedhelpmakesureyougetitfromsomeoneyoutrustandnotfromrandomidiotsontheinternet

DoMoreThisexercisehasalargeldquodomorerdquopartTheotherexercisesarenotasinvolvedasthisonebutIrsquomhavingyouprimeyourbrainfortherestoftheappendixbydoingsomememorizationJusttrustmethiswillmakethingssilkysmoothlateronLinuxmacOS

TakethislistofcommandsandcreateindexcardswiththenamesontheleftononesideandthedefinitionsontheothersideDrillthemeverydaywhilecontinuingwiththelessonsinthisappendix

pwdprintworkingdirectoryhostnamemycomputerrsquosnetworkname

mkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectorymvmoveafileordirectorylesspagethroughafilecatprintthewholefilexargsexecuteargumentsfindfindfilesgrepfindthingsinsidefilesmanreadamanualpageaproposfindwhichmanualpageisappropriateenvlookatyourenvironmentechoprintsomeargumentsexportexportsetanewenvironmentvariableexitexittheshellsudoDANGERbecomesuperuserrootDANGER

Windows

IfyoursquoreusingWindowsthenherersquosyourlistofcommandspwdprintworkingdirectoryhostnamemycomputerrsquosnetworknamemkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectory

robocopyrobustcopymvmoveafileordirectorymorepagethroughafiletypeprintthewholefileforfilesrunacommandonlotsoffilesdir-rfindfilesselect-stringfindthingsinsidefileshelpreadamanualpagehelpctrfindwhatmanualpageisappropriateechoprintsomeargumentssetexportsetanewenvironmentvariableexitexittheshellrunasDANGERbecomesuperuserrootDANGER

DrilldrilldrillDrilluntilyoucansaythesephrasesrightawaywhenyouseethatwordThendrilltheinversesothatyoureadthephraseandknowwhatcommandwilldothatYoursquorebuildingyourvocabularybydoingthisbutdonrsquotspendsomuchtimeyougonutsandgetbored

PathsFoldersDirectories(pwd)Inthisexerciseyoulearnhowtoprintyourworkingdirectorywiththepwdcommand

DoThisIrsquomgoingtoteachyouhowtoreadtheseldquosessionsrdquothatIshowyouYoudonrsquothavetotypeeverythingIlistherejustsomeoftheparts

bullYoudonottypeinthe$(Unix)orlt(Windows)ThatrsquosjustmeshowingyoumysessionsoyoucanseewhatIgot

bullYoutypeinthestuffafter$orltthenhitEnterSoifIhave$pwdyoutypejustpwdandhitEnter

bullYoucanthenseewhatIhaveforoutputfollowedbyanother$orltpromptThatcontentistheoutputandyoushouldseethesameoutput

LetrsquosdoasimplefirstcommandsoyoucangetthehangofthisLinuxmacOS

Exercise2Session

$pwd

Userszedshaw

$

Windows

Exercise2WindowsSession

PSCUserszedgtpwd

Path

----

CUserszed

PSCUserszedlt

WarningInthisappendixIneedtosavespacesothatyoucanfocusontheimportantdetailsofthecommandsTodothisIrsquomgoingtostripoutthefirstpartoftheprompt(thePSCUserszedabove)andleavejustthelittlegtpartThismeansyourpromptwonrsquotlookexactlythesamebutdonrsquotworryaboutthatRememberthatfromnowonIrsquollonlyhavethegttotellyouthatrsquosthepromptIrsquomdoingthesamethingfortheUnixpromptsbutUnixpromptsaresovariedthatmostpeoplegetusedto$meaningldquojustthepromptrdquo

YouLearnedThisYourpromptwilllookdifferentfrommineYoumayhaveyourusernamebeforethe$andthenameofyourcomputerOnWindowsitwillprobablylookdifferenttooThekeyisthatyouseethefollowingpattern

bullTherersquosapromptbullYoutypeacommandthereInthiscaseitrsquospwdbullItprintedsomethingbullRepeat

Youjustlearnedwhatpwddoeswhichmeansldquoprintworkingdirectoryrdquo

WhatrsquosadirectoryItrsquosafolderFolderanddirectoryarethesamethingandtheyrsquoreusedinterchangeablyWhenyouopenyourfilebrowseronyourcomputertographicallyfindfilesyouarewalkingthroughfoldersThosefoldersaretheexactsamethingsastheseldquodirectoriesrdquowersquoregoingtoworkwith

DoMorebullTypepwd20timesandeachtimesayldquoprintworkingdirectoryrdquobullWritedownthepaththatthiscommandgivesyouFinditwithyourgraphicalfilebrowserofchoice

bullNoseriouslytypeit20timesandsayitoutloudSsshJustdoit

IfYouGetLostAsyougothroughtheseinstructionsyoumaygetlostYoumaynotknowwhereyouareorwhereafileisandhavenoideahowtocontinueTosolvethisproblemIamgoingtoteachyouthecommandstotypetostopbeinglostWheneveryougetlostitismostlikelybecauseyouweretypingcommandsandhavenoideawhereyoursquoveendedupWhatyoushoulddoistypepwdtoprintyourcurrentdirectoryThistellsyouwhereyouareThenextthingisyouneedtohaveawayofgettingbacktowhereyouaresafeyourhomeTodothistypecd~andyouarebackinyourhomeThismeansifyougetlostatanytimetype

pwd

cd~

ThefirstcommandpwdtellsyouwhereyouareThesecondcommandcd~takesyouhomesoyoucantryagain

DoThisRightnowfigureoutwhereyouareandthengohomeusingpwdandcd~Thiswillmakesureyouarealwaysintherightplace

YouLearnedThisHowtogetbacktoyourhomeifyouevergetlost

MakeaDirectory(mkdir)Inthisexerciseyoulearnhowtomakeanewdirectory(folder)usingthemkdircommand

DoThis

DoThisRememberYouneedtogohomefirstDoyourpwdthencd~beforedoingthisexerciseBeforeyoudoallexercisesinthisappendixalwaysgohomefirstLinuxmacOS

Clickheretoviewcodeimage

Exercise4Session

$pwd

$cd~

$mkdirtemp

$mkdirtempstuff

$mkdirtempstuffthings

$mkdir-ptempstuffthingsorangeapplepeargrape

$

Windows

Clickheretoviewcodeimage

Exercise4WindowsSession

gtpwd

gtcd~

gtmkdirtemp

DirectoryCUserszed

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMtemp

gtmkdirtempstuff

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMstuff

gtmkdirtempstuffthings

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtmkdirtempstuffthingsorangeapplepeargrape

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gt

ThisistheonlytimeIrsquolllistthepwdandcd~commandsTheyareexpectedintheexerciseseverytimeDothemallthetime

YouLearnedThisNowwegetintotypingmorethanonecommandTheseareallthedifferentwaysyoucanrunmkdirWhatdoesmkdirdoItmakesdirectoriesWhyareyouaskingthatYoushouldbedoingyourindexcardsandgettingyourcommandsmemorizedIfyoudonrsquotknowthatldquomkdirmakesdirectoriesrdquothenkeepworkingtheindexcardsWhatdoesitmeantomakeadirectoryYoumightcalldirectoriesldquofoldersrdquoTheyrsquorethesamethingAllyoudidaboveiscreatedirectoriesinsidedirectoriesinsideofmoredirectoriesThisiscalledaldquopathrdquoanditrsquosawayofsayingldquofirsttempthenstuffthenthingsandthatrsquoswhereIwantitrdquoItrsquosasetofdirectionstothecomputerofwhereyouwanttoputsomethinginthetreeoffolders(directories)thatmakeupyourcomputerrsquosharddisk

WarningInthisappendixIrsquomusingthe(slash)characterforallpathssincetheyworkthesameonallcomputersnowHoweverWindowsuserswillneedtoknowthatyoucanalsousethe(backslash)characterandotherWindowsuserswilltypicallyexpectthatattimes

DoMorebullTheconceptofaldquopathrdquomightconfuseyouatthispointDonrsquotworryWersquolldoalotmorewiththemandthenyoursquollgetit

bullMake20otherdirectoriesinsidethetempdirectoryinvariouslevelsGolookatthemwithagraphicalfilebrowser

bullMakeadirectorywithaspaceinthenamebyputtingquotesarounditmkdirIHaveFun

bullIfthetempdirectoryalreadyexiststhenyoursquollgetanerrorUsecdtochangetoaworkdirectorythatyoucancontrolandtryitthereOnWindowsDesktopisagoodplace

ChangeDirectory(cd)Inthisexerciseyoulearnhowtochangefromonedirectorytoanotherusingthecdcommand

DoThisIrsquomgoingtogiveyoutheinstructionsforthesesessionsonemoretime

bullYoudonottypeinthe$(Unix)orgt(Windows)bullYoutypeinthestuffafterthisthenhitEnterIfIhave$cdtempyoujusttypecdtempandhitEnter

bullTheoutputcomesafteryouhitEnterfollowedbyanother$orgtpromptbullAlwaysgohomefirstDopwdandthencd~soyougobacktoyourstartingpoint

LinuxmacOS

Clickheretoviewcodeimage

Exercise5Session

$cdtemp

$pwd

~temp

$cdstuff

$pwd

~tempstuff

$cdthings

$pwd

~tempstuffthings

$cdorange

$pwd

~tempstuffthingsorange

$cdapple

$pwd

~tempstuffthingsorangeapple

$cdpear

$pwd

~tempstuffthingsorangeapplepear

$cdgrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$cd

$pwd

~tempstuffthingsorangeapple

$cd

$cd

$pwd

~tempstuffthings

$cd

$pwd

~

$cdtempstuffthingsorangeapplepeargrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$pwd

~

$

Windows

Clickheretoviewcodeimage

Exercise5WindowsSession

gtcdtemp

gtpwd

Path

----

CUserszedtemp

gtcdstuff

gtpwd

Path

----

CUserszedtempstuff

gtcdthings

gtpwd

Path

----

CUserszedtempstuffthings

gtcdorange

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcdapple

gtpwd

Path

----

CUserszedtempstuffthingsorangeapple

gtcdpear

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepear

gtcdgrape

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepeargrape

gtcd

gtcd

gtcd

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcd

gtpwd

Path

----

CUserszedtempstuff

gtcd

gtcd

gtcdtempstuffthingsorangeapplepeargrape

gtcd

gtpwd

Path

----

CUserszed

gt

YouLearnedThisYoumadeallthesedirectoriesinthelastexerciseandnowyoursquorejustmovingaroundinsidethemwiththecdcommandInmysessionaboveIalsousepwdtocheckwhereIamsoremembernottotypetheoutputthatpwdprintsForexampleonline3yousee~tempbutthatrsquostheoutputofpwdfromthepromptaboveitDonottypethisinYoushouldalsoseehowIusethetomoveldquouprdquointhetreeandpath

DoMoreAveryimportantpartoflearningtousethecommandlineinterface(CLI)onacomputerwithagraphicaluserinterface(GUI)isfiguringouthowtheyworktogetherWhenIstartedusingcomputerstherewasnoGUIandyoudideverythingwiththeDOSprompt(theCLI)LaterwhencomputersbecamepowerfulenoughthateveryonecouldhavegraphicsitwassimpleformetomatchCLIdirectorieswithGUIwindowsandfoldersMostpeopletodayhoweverhavenocomprehensionoftheCLIpathsanddirectoriesInfactitrsquosverydifficulttoteachittothemandtheonlywaytolearnabouttheconnectionisforyoutoconstantlyworkwiththeCLIuntilonedayitclicksthatthingsyoudointheGUIwillshowupintheCLI

dayitclicksthatthingsyoudointheGUIwillshowupintheCLIThewayyoudothisisbyspendingsometimefindingdirectorieswithyourGUIfilebrowserthengoingtothemwithyourCLIThisiswhatyoursquolldonext

bullcdtotheappledirectorywithonecommandbullcdbacktotempwithonecommandbutnotfurtherabovethatbullFindouthowtocdtoyourldquohomedirectoryrdquowithonecommandbullcdtoyourDocumentsdirectorythenfinditwithyourGUIfilebrowser(FinderWindowsExploreretc)

bullcdtoyourDownloadsdirectorythenfinditwithyourfilebrowserbullFindanotherdirectorywithyourfilebrowserthencdtoitbullRememberwhenyouputquotesaroundadirectorywithspacesinitYoucandothatwithanycommandForexampleifyouhaveadirectoryIHaveFunthenyoucandocdIHaveFun

ListDirectory(ls)Inthisexerciseyoulearnhowtolistthecontentsofadirectorywiththelscommand

DoThisBeforeyoustartmakesureyoucdbacktothedirectoryabovetempIfyouhavenoideawhereyouareusepwdtofigureitoutandthenmovethereLinuxmacOS

Exercise6Session

$cdtemp

$ls

stuff

$cdstuff

$ls

things

$cdthings

$ls

orange

$cdorange

$ls

apple

$cdapple

$ls

pear

$cdpear

$ls

$cdgrape

$ls

$cd

$ls

grape

$cd

$ls

orange

$cd

$ls

stuff

$

Windows

Clickheretoviewcodeimage

Exercise6WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuff

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcdthings

gtls

DirectoryCUserszedtempstuffthings

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMorange

gtcdorange

gtls

DirectoryCUserszedtempstuffthingsorange

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMapple

gtcdapple

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcdpear

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcdgrape

gtls

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gt

YouLearnedThisThelscommandlistsoutthecontentsofthedirectoryyouarecurrentlyinYoucanseemeusecdtochangeintodifferentdirectoriesandthenlistwhatrsquosinthemsoIknowwhichdirectorytogotonextTherearealotofoptionsforthelscommandbutyoursquolllearnhowtogethelponthoselaterwhenwecoverthehelpcommand

DoMore

bullTypeeveryoneofthesecommandsinYouhavetoactuallytypethesetolearnthemJustreadingthemisnotgoodenoughIrsquollstopyellingnow

bullOnUnixtrythels-lRcommandwhileyoursquoreintempbullOnWindowsdothesamethingwithdir-RbullUsecdtogettootherdirectoriesonyourcomputerandthenuselstoseewhatrsquosinthem

bullUpdateyournotebookwithnewquestionsIknowyouprobablyhavesomebecauseIrsquomnotcoveringeverythingaboutthiscommand

bullRememberthatifyougetlostuselsandpwdtofigureoutwhereyouareandthengotowhereyouneedtobewithcd

RemoveDirectory(rmdir)Inthisexerciseyoulearnhowtoremoveanemptydirectory

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise7Session

$cdtemp

$ls

stuff

$cdstuffthingsorangeapplepeargrape

$cd

$rmdirgrape

$cd

$rmdirpear

$cd

$ls

apple

$rmdirapple

$cd

$ls

orange

$rmdirorange

$cd

$ls

things

$rmdirthings

$cd

$ls

stuff

$rmdirstuff

$pwd

~temp

$

WarningIfyoutrytodormdironmacOSanditrefusestoremovethedirectoryeventhoughyouarepositiveitrsquosemptythenthereisactuallyafileintherecalledDS_StoreInthatcasetyperm-rfltdirgtinstead(replaceltdirgtwiththedirectoryname)

Windows

Clickheretoviewcodeimage

Exercise7WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuffthingsorangeapplepeargrape

gtcd

gtrmdirgrape

gtcd

gtrmdirpear

gtcd

gtrmdirapple

gtcd

gtrmdirorange

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMthings

gtrmdirthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMstuff

gtrmdirstuff

gtpwd

Path

----

CUserszedtemp

gtcd

gt

YouLearnedThisIrsquomnowmixingupthecommandssomakesureyoutypethemexactlyandpayattentionEverytimeyoumakeamistakeitrsquosbecauseyouarenrsquotpayingattentionIfyoufindyourselfmakingmanymistakesthentakeabreakorjustquitforthedayYoursquovealwaysgottomorrowtotryagainInthisexampleyoursquolllearnhowtoremoveadirectoryItrsquoseasyYoujustgotothedirectoryrightaboveitthentypermdirltdirgtreplacingltdirgtwiththenameofthedirectorytoremove

DoMorebullMake20moredirectoriesandremovethemallbullMakeasinglepathofdirectoriesthatis10deepandremovethemoneatatimejustlikeIdidpreviously

bullIfyoutrytoremoveadirectorywithcontentsyouwillgetanerrorIrsquollshowyouhowtoremovethoseinlaterexercises

MovingAround(pushdpopd)InthisexerciseyoulearnhowtosaveyourcurrentlocationandgotoanewlocationwithpushdYouthenlearnhowtoreturntothesavedlocationwithpopd

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise8Session

$cdtemp

$mkdirilikeicecream

$pushdilikeicecream

~tempilikeicecream~temp

$popd

~temp

$pwd

~temp

$pushdilike

tempiliketemp

$pwd

~tempilike

$pushdicecream

~tempilikeicecreamtempiliketemp

$pwd

~tempilikeicecream

$popd

tempiliketemp

$pwd

~tempilike

$popd

~temp

$pushdilikeicecream

~tempilikeicecream~temp

$pushd

~temp~tempilikeicecream

$pwd

~temp

$pushd

~tempilikeicecream~temp

$pwd

~tempilikeicecream

$

Windows

Windows

Clickheretoviewcodeimage

Exercise8WindowsSession

gtcdtemp

gtmkdirilikeicecream

DirectoryCUserszedtempilike

ModeLastWriteTimeLengthName

---------------------------

d----122020111105AMicecream

gtpushdilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtemp

gtpushdilike

gtpwd

Path

----

CUserszedtempilike

gtpushdicecream

gtpwd

Path

----

CUserszedtempilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtempilike

gtpopd

gt

WarningInWindowsyounormallydonrsquotneedthe-poptionlikeyoudoinLinuxHoweverIbelievethisisamorerecentdevelopmentsoyoumayrunintoolderWindowsPowerShellversionsthatdorequirethe-pIfyouhavemoreinformationonthispleaseemailmeathelplearncodethehardwayorgsoIcansortoutwhethertomention-pforWindowsornot

YouLearnedThisYoursquoregettingintoprogrammerterritorywiththesecommandsbuttheyrsquoresohandyIhavetoteachthemtoyouThesecommandsletyoutemporarilygotoadifferentdirectoryandthencomebackeasilyswitchingbetweenthetwoThepushdcommandtakesyourcurrentdirectoryandldquopushesrdquoitintoalistforlaterthenitchangestoanotherdirectoryItrsquoslikesayingldquoSavewhereIamthengohererdquoThepopdcommandtakesthelastdirectoryyoupushedandldquopopsrdquoitofftakingyoubackthereFinallyonUnixpushdifyourunitbyitselfwithnoargumentsitwillswitchbetweenyourcurrentdirectoryandthelastoneyoupushedItrsquosaneasywaytoswitchbetweentwodirectoriesThisdoesnotworkinPowerShell

DoMorebullUsethesecommandstomovearounddirectoriesalloveryourcomputerbullRemovetheilikeicecreamdirectoriesandmakeyourownthenmovearoundinthem

bullExplaintoyourselftheoutputthatpushdandpopdwillprintoutforyouNoticehowitworkslikeastack

bullYoualreadyknowthisbutrememberthatmkdir-p(onLinuxmacOS)willmakeanentirepathevenifallthedirectoriesdonrsquotexistThatrsquoswhatIdidfirstforthisexercise

bullRememberthatWindowswillmakeafullpathanddoesnotneedthe-p

MakingEmptyFiles(touchNew-Item)Inthisexerciseyoulearnhowtomakeanemptyfileusingthetouch(New-ItemonWindows)command

DoThisLinuxmacOS

Exercise9Session

$cdtemp

$touchiamcooltxt

$ls

iamcooltxt

$

Windows

Clickheretoviewcodeimage

Exercise9WindowsSession

gtcdtemp

gtNew-Itemiamcooltxt-typefile

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12172011903AMiamcooltxt

gt

YouLearnedThisYoulearnedhowtomakeanemptyfileOnUnixtouchdoesthisanditalsochangesthetimesonthefileIrarelyuseitforanythingotherthanmakingemptyfilesOnWindowsyoudonrsquothavethiscommandsoyoulearnedhowtousetheNew-Itemcommandwhichdoesthesamethingbutcanalsomakenewdirectories

DoMorebullUnixMakeadirectorychangetoitandthenmakeafileinitThenchangeonelevelupandrunthermdircommandinthisdirectoryYoushouldgetanerrorTrytounderstandwhyyougotthiserror

bullWindowsDothesamethingbutyouwonrsquotgetanerrorYoursquollgetapromptaskingifyoureallywanttoremovethedirectory

CopyaFile(cp)Inthisexerciseyoulearnhowtocopyafilefromonelocationtoanotherwiththecpcommand

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise10Session

$cdtemp

$cpiamcooltxtneattxt

$ls

iamcooltxtneattxt

$cpneattxtawesometxt

$ls

awesometxtiamcooltxtneattxt

$cpawesometxtthefourthfiletxt

$ls

awesometxtiamcooltxtneattxtthefourthfiletxt

$mkdirsomething

$cpawesometxtsomething

$ls

awesometxtiamcooltxtneattxtsomethingthefourthfiletxt

$lssomething

awesometxt

$cp-rsomethingnewplace

$lsnewplace

awesometxt

$

Windows

Clickheretoviewcodeimage

Exercise10WindowsSession

gtcdtemp

gtcpiamcooltxtneattxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpneattxtawesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpawesometxtthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtmkdirsomething

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

gtcpawesometxtsomething

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtlssomething

DirectoryCUserszedtempsomething

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtcp-recursesomethingnewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gt

YouLearnedThisNowyoucancopyfilesItrsquossimpletojusttakeafileandcopyittoanewoneInthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectory

InthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectoryIrsquomgoingtotellyouasecretaboutprogrammersandsystemadministratorsnowTheyarelazyIrsquomlazyMyfriendsarelazyThatrsquoswhyweusecomputersWeliketomakecomputersdoboringthingsforusIntheexercisessofaryouhavebeentypingrepetitiveboringcommandssothatyoucanlearnthembutusuallyitrsquosnotlikethisUsuallyifyoufindyourselfdoingsomethingboringandrepetitivetherersquosprobablyaprogrammerwhohasfiguredouthowtomakeiteasierYoujustdonrsquotknowaboutityetTheotherthingaboutprogrammersistheyarenrsquotnearlyascleverasyouthinkIfyouoverthinkwhattotypethenyoursquollprobablygetitwrongInsteadtrytoimaginewhatthenameofacommandistoyouandtryitChancesarethatitrsquosanameorsomeabbreviationsimilartowhatyouthoughtitwasIfyoustillcanrsquotfigureitoutintuitivelythenaskaroundandsearchonlineHopefullyitrsquosnotsomethingreallystupidlikeROBOCOPY

DoMorebullUsethecp-rcommandtocopymoredirectorieswithfilesinthembullCopyafiletoyourhomedirectoryordesktopbullFindthesefilesinyourGUIandopentheminatexteditorbullNoticehowsometimesIputa(slash)attheendofadirectoryThatmakessurethefileisreallyadirectorysoifthedirectorydoesnrsquotexistIrsquollgetanerror

MovingaFile(mv)Inthisexerciseyoulearnhowtomoveafilefromonelocationtoanotherusingthemvcommand

DoThisLinuxmacOS

Exercise11Session

$cdtemp

$mvawesometxtuncooltxt

$ls

newplaceuncooltxt

$mvnewplaceoldplace

$ls

oldplaceuncooltxt

$mvoldplacenewplace

$ls

newplaceuncooltxt

$

Windows

Clickheretoviewcodeimage

Exercise11WindowsSession

gtcdtemp

gtmvawesometxtuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvnewplaceoldplace

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMoldplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvoldplacenewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gt

YouLearnedThisMovingfilesorratherrenamingthemItrsquoseasygivetheoldnameandthenewname

DoMoreMoveafileinthenewplacedirectorytoanotherdirectorythenmoveitback

ViewaFile(lessmore)TodothisexerciseyoursquoregoingtodosomeworkusingthecommandsyouknowsofarYoursquollalsoneedatexteditorthatcanmakeplaintext(txt)filesHerersquoswhatyoudo

bullOpenyourtexteditorandtypesomestuffintoanewfileOnmacOSthiscouldbeTextWranglerOnWindowsthismightbeNotepad++OnLinuxthiscouldbegeditAnyeditorwillwork

bullSavethatfiletoyourdesktopandnameittesttxtbullInyourshellusethecommandsyouknowtocopythisfiletoyourtempdirectorythatyoursquovebeenworkingwith

Onceyoursquovedonethatcompletethisexercise

Onceyoursquovedonethatcompletethisexercise

DoThisLinuxmacOS

Exercise12Session

$lesstesttxt

[displaysfilehere]

$

ThatrsquositTogetoutoflessjusttypeq(asinquit)Windows

Exercise12WindowsSession

gtmoretesttxt

[displaysfilehere]

gt

WarningIntheprecedingoutputIrsquomshowing[displaysfilehere]toldquoabbreviaterdquowhatthatprogramshowsIrsquolldothiswhenImeantosayldquoShowingyoutheoutputofthisprogramistoocomplexsojustinsertwhatyouseeonyourcomputerhereandpretendIdidshowittoyourdquoYourscreenwillnotactuallyshowthis

YouLearnedThisThisisonewaytolookatthecontentsofafileItrsquosusefulbecauseifthefilehasmanylinesitwillldquopagerdquosothatonlyonescreenfulatatimeisvisibleIntheDoMoresectionyoursquollplaywiththissomemore

DoMorebullOpenyourtextfileagainandrepeatedlycopy-pastethetextsothatitrsquosabout50ndash100lineslong

bullCopyittoyourtempdirectoryagainsoyoucanlookatitbullNowdotheexerciseagainbutthistimepagethroughitOnUnixyouuse

thespacebarandw(theletterw)togodownandupArrowkeysalsoworkOnWindowsjusthitthespacebartopagethrough

bullLookatsomeoftheemptyfilesyoucreatedtoobullThecpcommandwilloverwritefilesthatalreadyexistsobecarefulcopyingfilesaround

StreamaFile(cat)YoursquoregoingtodosomemoresetupforthisonesoyougetusedtomakingfilesinoneprogramandthenaccessingthemfromthecommandlineWiththesametexteditorfromthelastexercisecreateanotherfilenamedtest2txtbutthistimesaveitdirectlytoyourtempdirectory

DoThisLinuxmacOS

Exercise13Session

$lesstest2txt

[displaysfilehere]

$cattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

$cattesttxt

Hitherethisiscool

$

Windows

Exercise13WindowsSession

gtmoretest2txt

[displaysfilehere]

gtcattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

gtcattesttxt

Hitherethisiscool

gt

RememberthatwhenIsay[displaysfilehere]IrsquomabbreviatingtheoutputofthatcommandsoIdonrsquothavetoshowyouexactlyeverything

YouLearnedThisDoyoulikemypoemTotallygoingtowinaNobelAnywayyoualreadyknowthefirstcommandandIrsquomjusthavingyoucheckthatyourfileisthereThenyoucatthefiletothescreenThiscommandjustspewsthewholefiletothescreenwithnopagingorstoppingTodemonstratethatIhaveyoudothistotesttxtwhichshouldjustspewabunchoflinesfromthatexercise

DoMorebullMakeafewmoretextfilesandworkwithcatbullUnixTrycattesttxttest2txtandseewhatitdoesbullWindowsTrycattesttxttest2txtandseewhatitdoes

RemovingaFile(rm)Inthisexerciseyoulearnhowtoremove(delete)afileusingthermcommand

DoThisLinux

Clickheretoviewcodeimage

Exercise14Session

$cdtemp

$ls

uncooltxtiamcooltxtneattxtsomethingthefourthfiletxt

$rmuncooltxt

$ls

iamcooltxtneattxtsomethingthefourthfiletxt

$rmiamcooltxtneattxtthefourthfiletxt

$ls

something

$cp-rsomethingnewplace

$

$rmsomethingawesometxt

$rmdirsomething

$rm-rfnewplace

$ls

$

Windows

Clickheretoviewcodeimage

Exercise14WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtrmuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtrmiamcooltxt

gtrmneattxt

gtrmthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

gtcp-rsomethingnewplace

gtrmsomethingawesometxt

gtrmdirsomething

gtrm-rnewplace

gtls

gt

YouLearnedThisHerewecleanupthefilesfromthelastexerciseRememberwhenIhadyoutrytormdironadirectorywithsomethinginitWellthatfailedbecauseyoucanrsquotremoveadirectorywithfilesinitTodothatyouhavetoremovethefileorrecursivelydeleteallofitscontentsThatrsquoswhatyoudidattheendofthis

DoMorebullCleanupeverythingintempfromalltheexercisessofarbullWriteinyournotebooktobecarefulwhenrunningrecursiveremoveonfiles

ExitingYourTerminal(exit)DoThisLinuxmacOS

Exercise23Session

$exit

Windows

Exercise23WindowsSession

gtexit

YouLearnedThisYourfinalexerciseishowtoexitaTerminalAgainthisisveryeasybutIrsquomgoingtohaveyoudomore

DoMore

ForyourlastsetofexercisesIrsquomgoingtohaveyouusethehelpsystemtolookupasetofcommandsyoushouldresearchandlearnhowtouseonyourownHerersquosthelistforUnix

bullxargsbullsudobullchmodbullchown

ForWindowslookupthesethingsbullforfilesbullrunasbullattribbullicacls

Findoutwhattheseareplaywiththemandthenaddthemtoyourindexcards

CommandLineNextStepsYouhavecompletedthecrashcourseAtthispointyoushouldbeabarelycapableshelluserTherersquosawholehugelistoftricksandkeysequencesyoudonrsquotknowyetandIrsquomgoingtogiveyouafewfinalplacestogoresearchmore

UnixBashReferencesTheshellyoursquovebeenusingiscalledBashItrsquosnotthegreatestshellbutitrsquoseverywhereandhasalotoffeaturessoitrsquosagoodstartHerersquosashortlistoflinksaboutBashyoushouldgoread

BashCheatSheethttpslearncodethehardwayorgunixbash_cheat_sheetpdf(createdbyRaphaelandCClicensed)

ReferenceManualhttpwwwgnuorgsoftwarebashmanualbashrefhtml

PowerShellReferencesOnWindowstherersquosreallyonlyPowerShellHerersquosalistofusefullinksforyourelatedtoPowerShell

OwnerrsquosManualhttptechnetmicrosoftcomen-uslibraryee221100aspx

CheatSheethttpsdownloadmicrosoftcomdownload2122122F0B9-0EE6-4E6D-BFD6-F9DCD27C07F9WS12_QuickRef_Download_FilesPowerShell_LangRef_v3pdf

MasterPowerShellhttppowershellcomcsblogsebookdefaultaspx

Index

Symbols(colon)creatingfunctions61ndash62(dot)operator146ndash148193(double-quotes)avoidusingwithTrueFalse31createstrings26ndash27createstringswithsingle-quotesvs29escapinginsidestrings34ndash36promptandpass47

gt=(greater-than-equal)operator16ndash1797+=(incrementby)operator69ndash70105lt=(less-than-equal)operator16ndash1797-(minus)operator16ndash17=(notequal)operator97ndash98100ndash102(single-quotes)createstrings26ndash27createstringswithdouble-quotesvs29escapinginsidestrings34ndash36indicatingstrings57

(triple-single-quotes)36(triple-quotes)dedentfunction170ndash175errorswhenputtingspacesbetween33escapinginsidestrings3436

(slash)character16ndash17257(backslash)character33ndash34257(doublebacklash)character36_(underscore)character20ndash2162189+(plus)operator16ndash1754==(equal)operatorfunctionof21

practicingBooleanlogic100ndash102intruthtables98astruthterm97

=(single-equal)operator21(poundoroctothorpe)character1214ndash1517(percent)operator1617ndash18(asterisk)operator16ndash17[]leftandrightbracketslists112ndash114^(caret)characterviewoutput11charactersembeddedvariablesinstrings24ndash25lt(lessthan)operator16ndash17ltgt=(notequal)vs102gt(greaterthan)operator16ndash1791

AactivatescriptPowershell195Addressesweb225altered()functioninheritance180ndash183Alternativetexteditors6ndash7and

inBooleanlogic100ndash102astruthterm96ndash98

apppy

buildfirstwebsite217ndash221creategameengine239ndash241createHTMLforms228ndash229howformswork226ndash227writeautomatedtestsforforms231ndash232

app_testspyfile231241aproposcommand252args60ndash62Argumentscreatingfunctions6266argv

asargumentvariable42

promptingandpassingusing46ndash47readingandwritingfiles54readingfiles48ndash50unpacking42ndash44usinginput()vs44

Arrayslistsvs114ASCII(AmericanStandardCodeforInformationInterchange)80ndash81assert_equal()functionautomatedtesting201ndash203assert_raises()functionwritingtestexpectedtofail215asterisk()operator16ndash17Atomtexteditoralternativesto6ndash7Linuxsetup4ndash5macOSsetup2Windowssetup3ndash4workingwithfirstprogram9

Automatedtestsforforms232improving242overviewof200ndash203refactoringgothonwebgameusing238ndash239testfirstwith206ndash207

BBackslash()character33ndash34257Bashreferences283Big5encoding85bindirectoryskeletonprojectdirectory198Bits8182Blocksofcode106ndash110Booleanlogicmemorizingvslearning98practicing100ndash102rulesforif-statements126

Bottomupprocessesvstopdown169Brackets([])lists112ndash114Branchesandfunctions122ndash124Breakingfiles8592232Browsercreateenginetorungamein234ndash241gettinginputfromSeeInputgettingfrombrowserhowitaccessesinformation225ndash226

Bytesbreakingfiles85conventionsforencoding80ndash81defined78dissectingcode82ndash84dissectingoutput82

CC3algorithmsuper()function183Cardinalnumberslists120ndash121137caret(^)characterviewoutput11catcommandprintwholefile57252278ndash279cdcommandchangedirectorymacOSLinux251overviewof258ndash260Windows252

cd~command255CharactersencodingSeeStringsbytesandcharacterencodingsimportanceoflearningnamesof76fortruthterms96ndash97

Checklistcreatingfunction62ChildclassesSeeInheritancevscompositionClassesaddsconsistencytoprogram146asblueprintsfornewmini-modules149codeandtestinOOP167ndash169

designhierarchyinOOP166ndash167inheritancevscompositionSeeInheritancevscompositionobject-orientedphrasedrill152ndash153object-orientedreadingtest154ndash155object-orientedworddrill152researchingPython137similaritytomodules147ndash148styling189astemplatesmintingnewobjects186

CLI(commandlineinterface)usingonGUI261closecommandclosefile52ndash53Codeavoidhardcodingfilenames48blocksof106ndash107classestesting167ndash169createonelineof57findingerrorsin132inheritancevscompositionforreusable185OOPanalysisanddesign170ndash176parser211ndash214practicingEnglishto155reading132readingbackwardSeeReadingcodebackwardreadingphrases156refactoringforgothonwebgame234ndash239researchingpieceof78styling190testingotherprogrammerrsquos94typingintoTerminalPowerShell50

Colon()creatingfunctions61ndash62Colorsintexteditors12Command-linecrashcoursechangedirectory(cd)258ndash261copyfile(cp)272ndash275

exityourterminal(exit)282howtouseappendix248ndash249introduction248listdirectory(ls)261ndash265makedirectory(mkdir)255ndash257makeemptyfiles(touchNew-Item)271ndash272memorizingthings249movearound(pushdpopd)268ndash271movefile(mv)275ndash276pathsfoldersdirectories(pwd)253ndash255PowerShellreferences283removedirectory(rmdir)265ndash268removefile(rm)280ndash281setup249ndash253streamfile(cat)278ndash279UnixBashreferences283viewfile(lessmore)277ndash278

Commandlineinterface(CLI)usingonGUI261Commandsconvertingargumentstostrings44asfunctionsandmethods50learning44

Commentsaddingwhenreadingcode132creatingfunctionswith65ndash66designingdebuggingwith127functionsfileswith69gettinghelpwithdocumentation92is-ahas-arelationshipsusing159ndash160readingwritingfilesusing53usinginPython14ndash15variablenames21writinggood190writingwhenyoudonotunderstandcode29124

Composition

Compositiondefined152overviewof184ndash185whentouseinheritanceor185

Connectionsweb225ndash226Conventionsforencodingtext80ndash81Copyingfileswritingscriptfor56ndash58cpcopyfileordirectorymacOSLinux251overviewof272ndash275Windows252

curlcommandgeneraterequesttypes232

DDatastructuresdictionariesas140ndash144listsascommon136ndash137

Datatypeslistof129DBES(DecodeBytesEncodeStrings)dissectingcode83ndash84Debuggingdesigningand126ndash127fixingerrorsinfirstwebsite219refactoredcode241

Decisionsmaking108ndash110dedent()function-stylestrings170ndash175def(createfunction)branchesandfunctions122ndash124creategameengine239ndash241defined152filesworkingwithfunctions68ndash70functionscanreturnsomething72ndash74functionsworkingwithvariables90ndash93is-ahas-arelationships159ndash160overviewof60ndash62inreadingtest154ndash155

delkeyworddeletefromdictionary141Designinganddebugging126ndash127dict

howformswork227understandingdictionaries140ndash144

Dictionariesexampleof141ndash143functionsof143ndash144listsvs140ndash141modulessimilarto146ndash147storescenesbynamein175

diefunctionif-statementrules126dir-rfindfilesinWindows253DirectoriescausesofImportErrors209ldquoHelloWorldrdquowebapplication217LinuxmacOScommand-linefor251skeletonprojectSeeSkeletonprojectdirectoryWindowscommand-linefor252

DjangoTutorial244Documentationcheckoutprojectsbuildsomethingusing244gettinghelpwithcomments92writinggoodcomments190

Dot()operator146ndash148193Doublebacklash()36Double-quotesSee(double-quotes)

Eechoprintsomearguments252253Elementsaccessinglist120ndash121elif

branchesandfunctions122ndash124andelse107makingdecisions108ndash110

else

branchesandfunctions122ndash124andif-statement106ndash107makingdecisions108ndash110rulesforif-statements126

Encodingsbytescharacter80ndash85envcommandlookatyourenvironment252EqualoperatorSee==(equal)operatorErrormessagesbuildingfirstwebsite218ndash219EOFError155ImportErrorSeeImportErrorsNameError47ParserError211ndash214printing29forspacesbetweentriple-quotes33forspellingmistakes33ValueErrorSeeValueErrorsvariablenames21viewingoutputinfirstprogram11whenmakingscriptshorter58

Escapesequencesfordifferentcharactersinstrings34ndash35practicing87readingandwritingfiles54reviewing130supportedbyPython35

exceptkeywordexceptions206Exceptionshowtoraise211ndash214andnumbers206

existscommandcopyingfiles56ndash58exitcommandexitshell124252282exportcommandexportnewenvironmentvariable252

F

Ffcharacterembeddingvariablesinsidestrings24ndash25promptingandpassing46ndash47inreadline()70usingwithfunctions69

Falsekeywordavoidquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98

Featuresaddingtoscript42alsocalledmodules42ndash43

FileTransferProtocol(FTP)andURLs225Filenames48ndash50Filescopying56ndash58creating50andfunctions68ndash70LinuxmacOScommand-linefor251ndash252reading48ndash50readingandwriting52ndash54Windowscommand-linefor252ndash253

findcommandfiles252Firstprogramcreate8ndash12flaskframeworkcreatebasictemplatesforwebsite219ndash221creategameengine239ndash241fixerrors218ndash219ImportErrorafterinstalling222installingforfirstwebsite216makeldquoHelloWorldrdquowebapplication216ndash217testingtricksforcreatingfakesessions242webpyvs221

whatisgoingon218FLASK_DEBUGnotsafetoactivateonInternet219Flowcharts132FoldersSeeDirectoriesfooOOP152for-loops

buildinglistswith112ndash114rulesfor126whentouselists137while-loopsvs118

forOOP154ndash155forfiles253formatfunction30ndash31Formatstringsformatterformat()30oldstyle130ndash131overviewof24ndash25readingandwritingfiles54

format()syntaxformattingstrings26ndash2730Formsautomatedtestsfor232creatingHTML227ndash229howtheywork226ndash227

FTP(FileTransferProtocol)andURLs225Functionsaccessinginmodulewith(dot)operator146ndash147alsocalledmethodscommands50branchesand122ndash124canreturnsomething72ndash74createchecklistfor62andfiles68ndash70overviewof60ndash62practicing87ndash8890ndash93readingcode132

replicatingimplicitinheritance184ndash185styling189usingprintvsreturnin93andvariables64ndash6687ndash88viewingcalls137

GGamestartofyourwebcreatingengine239ndash241overviewof234refactoring234ndash239yourfinalexam241ndash242

GamesanalysisanddesignSeeObject-orientedanalysisanddesignmakingyour188ndash191

gothonwebprojectanalysisofsimplegameengine165ndash169codefor170ndash176creatinglayouttemplate234ndash239makingintofirstwebapplication217ndash221refactoringcodecreatingwebenginetorun234ndash241

Grammarmakingsentences211215Greater-than-equal(gt=)operator16ndash1797Greaterthan(gt)operator16ndash1791grepcommandfindthingsinsidefiles252GUI(graphicaluserinterface)usingCLIon261

HHardcodedfilenamesavoid48has-arelationships152158ndash162ldquoHelloWorldrdquowebapplicationcreatebasictemplates219ndash221fixingerrors218ndash219

Helpcreatesystemfor242

gettingmodule92helpcommandWindows253helpctrcommandWindows253Hierarchyclass166ndash169hostname

mycomputerrsquosnetworkname251252understandURLs225

HTMLcreatebasictemplatesforwebsite219ndash221createforms227ndash229creategameengine239ndash241improveappearanceof242research232understandresponse226

HTTPrequests218244researchHTTPREC232understandURLs225

IIDLEavoidusing1231if-elsetry-exceptvs209if-statements

branchesandfunctions122ndash124elseand106ndash107loopsandlists112ndash114makedecisions83ndash84108ndash110overviewof104ndash105readcode132rulesfor126

Implicitinheritancecombinewithothertypesofinheritance182compositionvs184ndash185overviewof178ndash179

import

addfeaturestoscript42copyfiles56ndash58filewithmodules146makeagameyourself188objectsassimilarto148ndash149

ImportErrorsafterinstallingflask222causesof209242createskeletonprojectdirectory199

Incrementby(+=)operator69ndash70105Indentation61ndash62106index()

creategameengine239ndash241createHTMLforms229howformswork227

indexGEThandler224Inheritanceavoidmultiple178183185object-orientedphrasedrill152object-orientedreadingtest154ndash155object-orientedworddrill152

Inheritancevscompositionalterbehaviorbeforeorafter180ndash181implicitinheritance179overrideexplicitly180overviewof178reasonforsuper()183threekindsofinheritancecombined182ndash183understandcomposition184ndash185understandinheritance178ndash179usinginheritancevscomposition185usingsuper()with__init__()183

__init__functioninitializingnewlycreatedemptyobject149

inis-ahas-arelationships159ndash162runningreliablyforparentclass162tryingnottodotoomuchin189usingselfwhenmakingfunctionsforclasses151usingsuper()in183

input()

askingquestions38ndash39enteringownvalues74parameterto(gt)124parametersunpackingvariables42ndash44promptingandpassing46ndash47promptingpeople40ndash41readingfiles48ndash50

Inputadvanceduserourgamelexicon204ndash206overviewof204testfirstchallenge206ndash207whatyoushouldtest207ndash209

Inputgettingfrombrowserbreakingit232creatingHTMLforms227ndash229creatinglayouttemplate229ndash230howformswork226ndash227howwebworks224ndash226writingautomatedtestsforforms232

ltinputgttags229ndash230Instance152ndash153Instantiation148ndash149Internetflaskdebuggermodenotsafeon219Internetresearchcheckoutprojectstrytobuildsomething244findthings5ndash6functionsandfiles69importstatement57

object-orientedprogramming137151pydoc40ndash41readingfiles49

int()functionconvertingcommandlineargumentstrings44IPaddressesandURLs225is-arelationships152158ndash162

JJinja2Documentationtemplatelanguage221

KKeywordslistof128ndash129Kivy244

LLayouttemplatecreate232LearnCTheHardWay244LearnRubyTheHardWay244len()function5658lesscommandviewfileinmacOSLinux252277ndash278Less-than-equal(lt=)operator16ndash1797Lessthan(lt)operator16ndash17LexiconcreatinggamemakesentencesSeeSentencesmakingoverviewof204ndash206testfirstchallenge206ndash207whatyoushouldtest207ndash209

Librariesdefined43LinuxmacOSalternativetexteditorsfor7getterminalopenandworking250ndash251projectskeletonsetup192ndash194setupexercise4ndash5

LinuxmacOScommand-linecatstreamfile278ndash279

cdchangedirectory258ndash259261cpcopyfileordirectory272274ndash275exitexitshell282lessviewfile277ndash278listofcommands251ndash252lslistdirectory262265mkdirmakedirectory256ndash257mvmovefileordirectory275277pushdpopd(movedirectory)268ndash271pwdprintworkingdirectory253ndash255rmstreamfile278ndash279rmdirremovedirectory266268

Listsaccesselementsof120ndash121buildusingfor-loops112ndash114doingthingsto134ndash138making2-D114processinglistsofthings78whentouse137

localhost

buildfirstwebsite218221webconnection225

Logicmemorizing96ndash98practicingBoolean100ndash102

Loginresearchingwebapplication242Lookuptablesdictionariesas144Loopsandlists112ndash114for-loopsSeefor-loopsmakinginfinite124rulesfor126ndash127while-loopsSeewhile-loops

lpthwvirtualenvironmentskeletonproject193195

lslistdirectorymacOSLinux251overviewof261ndash265Windows252

MmacOSSeeLinuxmacOSmainfunctiondissectingcode83manreadmanualpageinmacOSLinux252Mapclassgothonwebprojectcode171storingscenesbynameindictionary175

Mapsanalysisofsimplegameengine165completinggame242withdictionaries143ndash144

matchfunctionparsercode212Math16ndash1839Memorizationofcommandsusingindexcards251ndash253learningcommandline249oflogic96ndash98tipsfor96

Methodresolutionorder(MRO)super()183Methodsalsocalledfunctionsandcommands50functionsvs189

Minus(--)operator16ndash17mkdirmakedirectorymacOSLinux251overviewof255ndash257Windows252

Modifiersreadingandwritingfiles54ModulescausesofImportErrors209

gettinghelpfor92overviewof146ndash147replicatingimplicitinheritancein184ndash185usingclassesvs147ndash148

morecommandviewfileinWindows252278MRO(methodresolutionorder)super()183Multipleinheritanceavoid178183185mvcommandmovefileordirectorymacOSLinux251overviewof275ndash277Windows252

NNameErrormessage47Namescreatingfunction62189definemodules42ndash43filenames48ndash50importanceoflearningsymbol76variable20ndash2260ndash62

NaturalLanguageToolKit244Nestedstructureslistsas112rulesforif-statements126

new-itemcommandcreateemptyfilesinWindows271ndash272Noneforsomefunctions93nosetestscommandautomatedtests201ndash203automatedtestsforforms231createskeletonprojectdirectory197ndash199syntaxerror203

not

inBooleanlogic100ndash102intruthtables97ndash98

astruthterm97Notequal(=)operator97ndash98100ndash102Nounsobject-orientedprogramming164ndash167Numbersaccesselementsoflists120ndash121exceptionsand206indexlistsinto140ndash141inputtodomath39andmath16ndash18betweenrangeofnumbers110roundingfloatingpoint25

OObject-orientedanalysisanddesignSeealsoGamestartofyourwebanalysisofsimplegameengine165codeclassesandtesttorunthem167ndash169codeforldquoGothonsfromPlanetPercal25rdquo170ndash176createclasshierarchyobjectmapforconcepts166ndash167extractresearchkeyconcepts166overviewof164ndash165repeatandrefine169topdownvsbottomup169whatyoushouldsee176writeordrawaboutproblem165

Object-orientedprogramming(OOP)inheritancevscompositionSeeInheritancevscompositionPythonas146research137151speak152ndash156

Objectsclassesastemplatesthatmintnew186makesentenceswith210ndash211object-orientedphrasedrill152ndash153object-orientedworddrill152parsercode212ndash215

similartoimport148ndash149Octothorpe()character1214ndash1517opencommandreadingandwritingfiles52ndash54OperatorsfindingmorePythonequality102listof131ndash132math16ndash17variablename20ndash22

or

inBooleanlogic100ndash102intruthtables97ndash98astruthterm96

Ordermaintainwithlists137Ordinalnumberslists120ndash121Outputoffirstprogram10ndash11ldquoHelloWorldrdquowebapplication217

override()functioninheritance189

PPandas244Paragraphsif-statementrules126Parametersreadingandwritingfiles54ParentclassesSeeInheritancevscompositionParsercode211ndash214playingwith214ndash215

ParserErrorexception211ndash214Passingpromptingand46ndash47PEMDASacronymorderofmathoperations18Percent()operator1617ndash18Phrasedrillsobject-oriented152ndash156pip36(orjustpip)createskeletonprojectdirectory192ndash195198ndash199installflasktobuildfirstwebsite216

planispherepyfile234ndash238

planisphere_testspyfile238ndash239Plus(+)operator16ndash1754popdcommandpopdirectorymacOSLinux251overviewof268ndash271Windows252

Portswebconnections225POSTautomatedtestsforforms231creatingHTMLforms227ndash229

Pound()character1214ndash1517PowerShellcreategameengine240infirstprogram11ndash12references283typingcodeinto50Windows10setupfor3ndash4195250ndash251

print

debugwith127readcodeusing132whenfunctionsusereturnvs93

Printstringswithmorecomplicatedformatting30ndash31moreexercisesin28ndash2932ndash33usingescapesequences34ndash36variables24ndash25

print_a_linepassincurrentlinenumber68ndash69print_linefunctiondissectingcode83ndash84print_twofunctioncreatefunctions60ndash61Programminglanguagesadvicefromoldprogrammer246ndash247checkoutprojectstrytobuildsomething244howtolearnnew245learningcommandlineSeeCommand-linecrashcourse

Projectskeleton192ndash194Promptsidentifyinappendixexercises254andpassing46ndash47people40ndash41

Prototypelanguages186Pseudocodetestfirstusing207pushdcommandpushdirectorymacOSLinux251overviewof268ndash271Windows252

pwdcommandprintworkingdirectorymacOSLinux251overviewof253ndash255Windows252

pyfilespassingvariablestoscript42ndash44pydoccommandpromptpeople40ndash41PyGame244PYTHONPATHenvironmentvariable240

Qquit()functionreloadPythonafter92

Rraisekeywordexceptions211213ndash214range()functionloops114Rawbytes7982ndash84readcommandreadcontentsoffile52ndash54Readingcode132codeoutloud190files48ndash50andwritingfiles52ndash54

Readingcodebackwardcommentsandpoundcharacters14

defined88printing29reasonsfor15understandinghowto22

readline()function52ndash53687083Refactoringcode234ndash239render_template()function220ndash221requestargsforms227Requestswebgeneratingtypesofwithcurl232learnclientsideofHTTP244process224ndash225understand225

Responsesweb226return

functions72ndash74object-orientedreadingtest155whenfunctionsuseprintvs93

rmstreamfile280ndash281rmdircommandremovedirectorymacOSLinux251overviewof265ndash268Windows252

Roomclassautomatedtests201ndash203creategameengine239ndash241refactorcodeforgothonwebgame234ndash239

round()functionfloatingpointnumbers25Rulesforif-statements126forloops126ndash127whentouseinheritanceorcomposition185

runascommanddangerinwindows252

S

Scanninginputlexicontuples205209Scenes(rooms)analysisofsimplegameengine165ndash167codeclassesforsimplegame167ndash169gothonwebprojectcode170ndash176makinggameyourself188ndash191whatyoushouldsee176

SciPy244ScraPy244Scriptslinkingfunctionsto61makingdecisions107passingvariablesto42ndash44

SearchenginesfindingthingsonInternet5ndash6howtotype(octothorp)character15

seek()functiondefined52ndash53doesnotsetcurrentlineto070researchforfile69

select-stringcommandfindthingsinsideWindowsfiles253self

__init__function148151is-ahas-arelationshipsand159ndash160object-orientedlanguage152ndash155

Sentencesmakingbreakingup205exceptions211grammar211matchandpeek210ndash211overviewof210parsercode211ndash215whatyoushouldtest215

Servershowbrowsersaccessinformationon226

setcommandexportsetnewenvironmentvariableinWindows253Setupexercisealternativetexteditors6ndash7findingthingsonInternet5ndash6Linux4ndash5macOS2ndash3overviewof2warningsforbeginners6Windows3ndash4

setuppyfileskeletonprojectdirectory196198ndash199Single-equal(=)operator21Single-quotesSee(single-quotes)Skeletonprojectdirectoryautomatedtesting200ndash203creatingdirectorystructure195ndash197macOSLinuxsetup192ndash194overviewof192requiredquiz198testingsetup197ndash198using198Windows10setup194ndash195

skipkeywordparsercode213Slash()character16ndash17257Spaceaddingaroundoperatorsforeasierreading22makecodereadablewithvertical190

Spellingmistakeserrormessagesfor33Stopwordsparsercode213Stringsacrossmultiplelines34ndash36complicatedformattingof30ndash31convertcommandlineargumentsto44decodebytesandencode83ndash84embedvariablesinside24ndash25

exerciseinprinting28ndash29listofescapesequencesfor130listofoldstyleformatsfor130ndash131listsmixedwith135ndash136poundcharactersin15readwritefilesin54startnewlinein33andtext26ndash27understanding26asUTF-8encodedsequenceofcharacters82

Stringsbytesandcharacterencodingsbreakingit85dissectcode82ndash84dissectoutput82encodingsdeepdive84ndash85initialresearch78ndash80overviewof78switchesandconventions80ndash81

Stylingcode190functionsandclasses189

Subjectparsercode212ndash215ofsentences210ndash211

sudocommand252super()functioninheritance180ndash183Switches80ndash81Symbolsdatatypes129escapesequencesforstrings130keywords128ndash129learningnamesof76oldstylestringformats130ndash131operators131ndash132readingcode132

SyntaxErrormessageEOL58invalidsyntax1293promptingandpassing47pydoc41viewingoutputinfirstprogram11

Systemsitepackagessetupforskeletonproject193

TTablesdictionariesaslookup144truth97ndash98

Templatescreatebasic219ndash221creategameengine239ndash241createHTMLforms229createlayout229ndash230

templatesindexhtmlfile219ndash221229ndash230templateslayouthtmlfile230TensorFlow244Terminalgettingopenandworking250ndash251Linuxsetup5macOSsetup2ndash3typingcodeinto50whatyoushouldseeinfirstprogram9ndash11Windowssetup3ndash4

Terminologytruth96ndash97webapplication225ndash226

Testcasewriting200ndash201Testfirstprogrammingtactic206ndash207Test_directionstestcase207ndash209TestsSeealsoAutomatedtestsBooleanlogic100ndash102

codeforclassesinOOP168ndash169object-orientedreading153ndash155otherprogrammerrsquoscode94session-basedgameengine241skeletonprojectdirectorysetup197ndash198tricksforcreatingfakesessionsinside242

testsapp_testspy231Testtxtfilecopyingfiles56ndash58Textreadingfiles48ndash50andstrings26ndash27

Texteditorsalternative6ndash7gettingcolorsin12Linuxsetup4ndash5macOSsetup2

Thingsgettingthingsfrom149ndash150TopdownprocessOOPdesign164vsbottomup169

touchcommandmakeemptyfilesinmacOSLinux271ndash272Tracingvariablesreadingcode132Triple-quotes()See(triple-quotes)Triple-single-quotes()36Truekeywordavoidputtingquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98astruthterm97

truncatecommand52ndash54Truthtables97ndash98terms96ndash97

try-exceptif-elsevs209

trykeywordexceptions206Tupleslexicon205typecommandprintwholefileinWindows252

UUnderscore(_)character20ndash2162189Unicode81URLs(UniformResourceLocators)buildfirstwebsite218createHTMLforms228howformswork227overviewof225

UserinputSeeInputadvanceduserUserWarningwhenrunningnosetests203UTF-16standard84ndash85UTF-8standardcomparingUTF-16UTF-32to84ndash85dissectingoutput82encodingtextinPython81fixingterminalunabletodisplay79stringsinPython82ndash84

VValueErrorsandnumbers206parametersunpackingvariables44promptingpassing47

Variablesaccessinmodule146ndash147avoidmoduleorglobal189andfunctions64ndash66for-loopusingundefined114andnames20ndash22andnamescodefunctions60ndash62passingtoscript42ndash44

practicing90ndash93printing24ndash25promptingandpassing46ndash47readingcode132temporarilyinsidefunctions87ndash88writingstringswithtext26ndash27

venvsdirectoryskeletonprojectsetup193ndash195VerbsanalyzeclasshierarchyinOOP165extractkeyconceptsinOOP164makesentenceswith210ndash211parsercode212ndash215

virtualenv192ndash193194

WWarningsforbeginners5ndash6setup2

Webbreakingapplications232howitworks224ndash226learnclientsideof244startofyourgameSeeGamestartofyourweb

Websiteyourfirstcreatebasictemplates219ndash221fixingerrors218ndash219installflaskframework216makeldquoHelloWorldrdquowebapplication216ndash217whatisgoingon218

while-loops

overviewof116ndash118readingcode132rules126whentobreakruleaboutnotusing138

whileTruemakeinfiniteloop124Windows

Windowsalternativetexteditorsfor7setupexercise3ndash4skeletonprojectdirectorysetup194ndash195

Windowscommand-linecatstreamfile259ndash261278ndash279cpcopyfileordirectory272ndash275exitexitshell282gettingPowerShellopenandworkingfor250ndash251listofcommands252ndash253lslistdirectory262ndash265macOSsetup2moreviewfile278mvmovefileordirectory275ndash277pushdpopd(movedirectory)269ndash271pwdprintworkingdirectory254ndash255rmstreamfile278ndash279rmdirremovedirectory266ndash268

Worddrillsobject-oriented152ndash155wordspopfunction93Writeformulasusingfunctions74andreadfiles52ndash54

Xxargscommandexecutearguments252

CodeSnippets

ManytitlesincludeprogrammingcodeorconfigurationexamplesTooptimizethepresentationoftheseelementsviewtheeBookinsingle-columnlandscapemodeandadjustthefontsizetothesmallestsettingInadditiontopresentingcodeandconfigurationsinthereflowabletextformatwehaveincludedimagesofthecodethatmimicthepresentationfoundintheprintbookthereforewherethereflowableformatmaycompromisethepresentationofthecodelistingyouwillseealdquoClickheretoviewcodeimagerdquolinkClickthelinktoviewtheprint-fidelitycodeimageToreturntothepreviouspageviewedclicktheBackbuttononyourdeviceorapp

  • About This eBook
  • Title Page
  • Copyright Page
  • Contents
  • Preface
    • Improvements in the Python 3 Edition
    • The Hard Way Is Easier
      • Reading and Writing
      • Attention to Detail
      • Spotting Differences
      • Ask Donrsquot Stare
      • Do Not Copy-Paste
      • Using the Included Videos
      • A Note on Practice and Persistence
        • Acknowledgments
          • Exercise 0 The Setup
            • macOS
              • macOS What You Should See
                • Windows
                  • Windows What You Should See
                    • Linux
                      • Linux What You Should See
                        • Finding Things on the Internet
                        • Warnings for Beginners
                        • Alternative Text Editors
                          • Exercise 1 A Good First Program
                            • What You Should See
                            • Study Drills
                            • Common Student Questions
                              • Exercise 2 Comments and Pound Characters
                                • What You Should See
                                • Study Drills
                                • Common Student Questions
                                  • Exercise 3 Numbers and Math
                                    • What You Should See
                                    • Study Drills
                                    • Common Student Questions
                                      • Exercise 4 Variables and Names
                                        • What You Should See
                                        • Study Drills
                                        • Common Student Questions
                                          • Exercise 5 More Variables and Printing
                                            • What You Should See
                                            • Study Drills
                                            • Common Student Questions
                                              • Exercise 6 Strings and Text
                                                • What You Should See
                                                • Study Drills
                                                • Break It
                                                • Common Student Questions
                                                  • Exercise 7 More Printing
                                                    • What You Should See
                                                    • Study Drills
                                                    • Break It
                                                    • Common Student Questions
                                                      • Exercise 8 Printing Printing
                                                        • What You Should See
                                                        • Study Drills
                                                        • Common Student Questions
                                                          • Exercise 9 Printing Printing Printing
                                                            • What You Should See
                                                            • Study Drills
                                                            • Common Student Questions
                                                              • Exercise 10 What Was That
                                                                • What You Should See
                                                                • Escape Sequences
                                                                • Study Drills
                                                                • Common Student Questions
                                                                  • Exercise 11 Asking Questions
                                                                    • What You Should See
                                                                    • Study Drills
                                                                    • Common Student Questions
                                                                      • Exercise 12 Prompting People
                                                                        • What You Should See
                                                                        • Study Drills
                                                                        • Common Student Questions
                                                                          • Exercise 13 Parameters Unpacking Variables
                                                                            • Hold Up Features Have Another Name
                                                                            • What You Should See
                                                                            • Study Drills
                                                                            • Common Student Questions
                                                                              • Exercise 14 Prompting and Passing
                                                                                • What You Should See
                                                                                • Study Drills
                                                                                • Common Student Questions
                                                                                  • Exercise 15 Reading Files
                                                                                    • What You Should See
                                                                                    • Study Drills
                                                                                    • Common Student Questions
                                                                                      • Exercise 16 Reading and Writing Files
                                                                                        • What You Should See
                                                                                        • Study Drills
                                                                                        • Common Student Questions
                                                                                          • Exercise 17 More Files
                                                                                            • What You Should See
                                                                                            • Study Drills
                                                                                            • Common Student Questions
                                                                                              • Exercise 18 Names Variables Code Functions
                                                                                                • What You Should See
                                                                                                • Study Drills
                                                                                                • Common Student Questions
                                                                                                  • Exercise 19 Functions and Variables
                                                                                                    • What You Should See
                                                                                                    • Study Drills
                                                                                                    • Common Student Questions
                                                                                                      • Exercise 20 Functions and Files
                                                                                                        • What You Should See
                                                                                                        • Study Drills
                                                                                                        • Common Student Questions
                                                                                                          • Exercise 21 Functions Can Return Something
                                                                                                            • What You Should See
                                                                                                            • Study Drills
                                                                                                            • Common Student Questions
                                                                                                              • Exercise 22 What Do You Know So Far
                                                                                                                • What You Are Learning
                                                                                                                  • Exercise 23 Strings Bytes and Character Encodings
                                                                                                                    • Initial Research
                                                                                                                    • Switches Conventions and Encodings
                                                                                                                    • Disecting the Output
                                                                                                                    • Disecting the Code
                                                                                                                    • Encodings Deep Dive
                                                                                                                    • Breaking It
                                                                                                                      • Exercise 24 More Practice
                                                                                                                        • What You Should See
                                                                                                                        • Study Drills
                                                                                                                        • Common Student Questions
                                                                                                                          • Exercise 25 Even More Practice
                                                                                                                            • What You Should See
                                                                                                                            • Study Drills
                                                                                                                            • Common Student Questions
                                                                                                                              • Exercise 26 Congratulations Take a Test
                                                                                                                                • Common Student Questions
                                                                                                                                  • Exercise 27 Memorizing Logic
                                                                                                                                    • The Truth Terms
                                                                                                                                    • The Truth Tables
                                                                                                                                    • Common Student Questions
                                                                                                                                      • Exercise 28 Boolean Practice
                                                                                                                                        • What You Should See
                                                                                                                                        • Study Drills
                                                                                                                                        • Common Student Questions
                                                                                                                                          • Exercise 29 What If
                                                                                                                                            • What You Should See
                                                                                                                                            • Study Drills
                                                                                                                                            • Common Student Questions
                                                                                                                                              • Exercise 30 Else and If
                                                                                                                                                • What You Should See
                                                                                                                                                • Study Drills
                                                                                                                                                • Common Student Questions
                                                                                                                                                  • Exercise 31 Making Decisions
                                                                                                                                                    • What You Should See
                                                                                                                                                    • Study Drills
                                                                                                                                                    • Common Student Questions
                                                                                                                                                      • Exercise 32 Loops and Lists
                                                                                                                                                        • What You Should See
                                                                                                                                                        • Study Drills
                                                                                                                                                        • Common Student Questions
                                                                                                                                                          • Exercise 33 While Loops
                                                                                                                                                            • What You Should See
                                                                                                                                                            • Study Drills
                                                                                                                                                            • Common Student Questions
                                                                                                                                                              • Exercise 34 Accessing Elements of Lists
                                                                                                                                                                • Study Drills
                                                                                                                                                                  • Exercise 35 Branches and Functions
                                                                                                                                                                    • What You Should See
                                                                                                                                                                    • Study Drills
                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                      • Exercise 36 Designing and Debugging
                                                                                                                                                                        • Rules for if-statements
                                                                                                                                                                        • Rules for Loops
                                                                                                                                                                        • Tips for Debugging
                                                                                                                                                                        • Homework
                                                                                                                                                                          • Exercise 37 Symbol Review
                                                                                                                                                                            • Keywords
                                                                                                                                                                            • Data Types
                                                                                                                                                                            • String Escape Sequences
                                                                                                                                                                            • Old Style String Formats
                                                                                                                                                                            • Operators
                                                                                                                                                                            • Reading Code
                                                                                                                                                                            • Study Drills
                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                              • Exercise 38 Doing Things to Lists
                                                                                                                                                                                • What You Should See
                                                                                                                                                                                • What Lists Can Do
                                                                                                                                                                                • When to Use Lists
                                                                                                                                                                                • Study Drills
                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                  • Exercise 39 Dictionaries Oh Lovely Dictionaries
                                                                                                                                                                                    • A Dictionary Example
                                                                                                                                                                                    • What You Should See
                                                                                                                                                                                    • What Dictionaries Can Do
                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                      • Exercise 40 Modules Classes and Objects
                                                                                                                                                                                        • Modules Are Like Dictionaries
                                                                                                                                                                                          • Classes Are Like Modules
                                                                                                                                                                                          • Objects Are Like Import
                                                                                                                                                                                          • Getting Things from Things
                                                                                                                                                                                          • A First Class Example
                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                              • Exercise 41 Learning to Speak Object-Oriented
                                                                                                                                                                                                • Word Drills
                                                                                                                                                                                                • Phrase Drills
                                                                                                                                                                                                • Combined Drills
                                                                                                                                                                                                • A Reading Test
                                                                                                                                                                                                • Practice English to Code
                                                                                                                                                                                                • Reading More Code
                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                  • Exercise 42 Is-A Has-A Objects and Classes
                                                                                                                                                                                                    • How This Looks in Code
                                                                                                                                                                                                    • About class Name(object)
                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                      • Exercise 43 Basic Object-Oriented Analysis and Design
                                                                                                                                                                                                        • The Analysis of a Simple Game Engine
                                                                                                                                                                                                          • Write or Draw About the Problem
                                                                                                                                                                                                          • Extract Key Concepts and Research Them
                                                                                                                                                                                                          • Create a Class Hierarchy and Object Map for the Concepts
                                                                                                                                                                                                          • Code the Classes and a Test to Run Them
                                                                                                                                                                                                          • Repeat and Refine
                                                                                                                                                                                                            • Top Down versus Bottom Up
                                                                                                                                                                                                            • The Code for ldquoGothons from Planet Percal 25rdquo
                                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                                              • Exercise 44 Inheritance versus Composition
                                                                                                                                                                                                                • What Is Inheritance
                                                                                                                                                                                                                  • Implicit Inheritance
                                                                                                                                                                                                                  • Override Explicitly
                                                                                                                                                                                                                  • Alter Before or After
                                                                                                                                                                                                                  • All Three Combined
                                                                                                                                                                                                                    • The Reason for super()
                                                                                                                                                                                                                      • Using super() with __init__
                                                                                                                                                                                                                        • Composition
                                                                                                                                                                                                                        • When to Use Inheritance or Composition
                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                          • Exercise 45 You Make a Game
                                                                                                                                                                                                                            • Evaluating Your Game
                                                                                                                                                                                                                            • Function Style
                                                                                                                                                                                                                            • Class Style
                                                                                                                                                                                                                            • Code Style
                                                                                                                                                                                                                            • Good Comments
                                                                                                                                                                                                                            • Evaluate Your Game
                                                                                                                                                                                                                              • Exercise 46 A Project Skeleton
                                                                                                                                                                                                                                • macOSLinux Setup
                                                                                                                                                                                                                                • Windows 10 Setup
                                                                                                                                                                                                                                • Creating the Skeleton Project Directory
                                                                                                                                                                                                                                  • Final Directory Structure
                                                                                                                                                                                                                                    • Testing Your Setup
                                                                                                                                                                                                                                    • Using the Skeleton
                                                                                                                                                                                                                                    • Required Quiz
                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                      • Exercise 47 Automated Testing
                                                                                                                                                                                                                                        • Writing a Test Case
                                                                                                                                                                                                                                        • Testing Guidelines
                                                                                                                                                                                                                                        • What You Should See
                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                          • Exercise 48 Advanced User Input
                                                                                                                                                                                                                                            • Our Game Lexicon
                                                                                                                                                                                                                                              • Breaking Up a Sentence
                                                                                                                                                                                                                                              • Lexicon Tuples
                                                                                                                                                                                                                                              • Scanning Input
                                                                                                                                                                                                                                              • Exceptions and Numbers
                                                                                                                                                                                                                                                • A Test First Challenge
                                                                                                                                                                                                                                                • What You Should Test
                                                                                                                                                                                                                                                • Study Drills
                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                  • Exercise 49 Making Sentences
                                                                                                                                                                                                                                                    • Match and Peek
                                                                                                                                                                                                                                                    • The Sentence Grammar
                                                                                                                                                                                                                                                    • A Word on Exceptions
                                                                                                                                                                                                                                                    • The Parser Code
                                                                                                                                                                                                                                                    • Playing with the Parser
                                                                                                                                                                                                                                                    • What You Should Test
                                                                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                                      • Exercise 50 Your First Website
                                                                                                                                                                                                                                                        • Installing flask
                                                                                                                                                                                                                                                        • Make a Simple ldquoHello Worldrdquo Project
                                                                                                                                                                                                                                                        • Whatrsquos Going On
                                                                                                                                                                                                                                                        • Fixing Errors
                                                                                                                                                                                                                                                        • Create Basic Templates
                                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                                          • Exercise 51 Getting Input from a Browser
                                                                                                                                                                                                                                                            • How the Web Works
                                                                                                                                                                                                                                                            • How Forms Work
                                                                                                                                                                                                                                                            • Creating HTML Forms
                                                                                                                                                                                                                                                            • Creating a Layout Template
                                                                                                                                                                                                                                                            • Writing Automated Tests for Forms
                                                                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                                                                            • Breaking It
                                                                                                                                                                                                                                                              • Exercise 52 The Start of Your Web Game
                                                                                                                                                                                                                                                                • Refactoring the Exercise 43 Game
                                                                                                                                                                                                                                                                • Creating an Engine
                                                                                                                                                                                                                                                                • Your Final Exam
                                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                                  • Next Steps
                                                                                                                                                                                                                                                                    • How to Learn Any Programming Language
                                                                                                                                                                                                                                                                      • Advice from an Old Programmer
                                                                                                                                                                                                                                                                      • Appendix Command Line Crash Course
                                                                                                                                                                                                                                                                        • Introduction Shut Up and Shell
                                                                                                                                                                                                                                                                          • How to Use This Appendix
                                                                                                                                                                                                                                                                          • You Will Be Memorizing Things
                                                                                                                                                                                                                                                                            • The Setup
                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                • Paths Folders Directories (pwd)
                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                    • If You Get Lost
                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                        • Make a Directory (mkdir)
                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                            • Change Directory (cd)
                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                • List Directory (ls)
                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                    • Remove Directory (rmdir)
                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                        • Moving Around (pushd popd)
                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                            • Making Empty Files (touchNew-Item)
                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                • Copy a File (cp)
                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                    • Moving a File (mv)
                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                        • View a File (lessmore)
                                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                                            • Stream a File (cat)
                                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                                • Removing a File (rm)
                                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                                    • Exiting Your Terminal (exit)
                                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                                        • Command Line Next Steps
                                                                                                                                                                                                                                                                                                                                          • Unix Bash References
                                                                                                                                                                                                                                                                                                                                          • PowerShell References
                                                                                                                                                                                                                                                                                                                                              • Index
                                                                                                                                                                                                                                                                                                                                              • Code Snippets
Page 3: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code

ManyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarksWherethosedesignationsappearinthisbookandthepublisherwasawareofatrademarkclaimthedesignationshavebeenprintedwithinitialcapitallettersorinallcapitals

TheauthorandpublisherhavetakencareinthepreparationofthisbookbutmakenoexpressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsoromissionsNoliabilityisassumedforincidentalorconsequentialdamagesinconnectionwithorarisingoutoftheuseoftheinformationorprogramscontainedherein

Forinformationaboutbuyingthistitleinbulkquantitiesorforspecialsalesopportunities(whichmayincludeelectronicversionscustomcoverdesignsandcontentparticulartoyourbusinesstraininggoalsmarketingfocusorbrandinginterests)pleasecontactourcorporatesalesdepartmentatcorpsalespearsonedcomor(800)382-3419

Forgovernmentsalesinquiriespleasecontactgovernmentsalespearsonedcom

ForquestionsaboutsalesoutsidetheUSpleasecontactintlcspearsoncom

VisitusontheWebinformitcomaw

LibraryofCongressControlNumber2017940290

Copyrightcopy2017ZedAShaw

AllrightsreservedPrintedintheUnitedStatesofAmericaThispublicationisprotectedbycopyrightandpermissionmustbeobtainedfromthepublisherpriortoanyprohibitedreproductionstorageinaretrievalsystemortransmissioninanyformorbyanymeanselectronicmechanicalphotocopyingrecordingorlikewiseForinformationregardingpermissionsrequestformsandtheappropriatecontactswithinthePearsonEducationGlobalRightsampPermissionsDepartmentpleasevisitwwwpearsonedcompermissions

ISBN-13978-0-13-469288-3ISBN-100-13-469288-8

117

Contents

Preface

ImprovementsinthePython3EditionTheHardWayIsEasier

ReadingandWritingAttentiontoDetailSpottingDifferencesAskDonrsquotStareDoNotCopy-PasteUsingtheIncludedVideosANoteonPracticeandPersistence

Acknowledgments

Exercise0TheSetupmacOS

macOSWhatYouShouldSeeWindows

WindowsWhatYouShouldSeeLinux

LinuxWhatYouShouldSeeFindingThingsontheInternetWarningsforBeginnersAlternativeTextEditors

Exercise1AGoodFirstProgramWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise2CommentsandPoundCharactersWhatYouShouldSee

StudyDrillsCommonStudentQuestions

Exercise3NumbersandMathWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise4VariablesandNamesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise5MoreVariablesandPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise6StringsandTextWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise7MorePrintingWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise8PrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise9PrintingPrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise10WhatWasThatWhatYouShouldSeeEscapeSequencesStudyDrillsCommonStudentQuestions

Exercise11AskingQuestionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise12PromptingPeopleWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise13ParametersUnpackingVariablesHoldUpFeaturesHaveAnotherNameWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise14PromptingandPassingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise15ReadingFilesWhatYouShouldSeeStudyDrills

CommonStudentQuestions

Exercise16ReadingandWritingFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise17MoreFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise18NamesVariablesCodeFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise19FunctionsandVariablesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise20FunctionsandFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise21FunctionsCanReturnSomethingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise22WhatDoYouKnowSoFarWhatYouAreLearning

Exercise23StringsBytesandCharacterEncodings

InitialResearchSwitchesConventionsandEncodingsDisectingtheOutputDisectingtheCodeEncodingsDeepDiveBreakingIt

Exercise24MorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise25EvenMorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise26CongratulationsTakeaTestCommonStudentQuestions

Exercise27MemorizingLogicTheTruthTermsTheTruthTablesCommonStudentQuestions

Exercise28BooleanPracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise29WhatIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise30ElseandIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise31MakingDecisionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise32LoopsandListsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise33WhileLoopsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise34AccessingElementsofListsStudyDrills

Exercise35BranchesandFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise36DesigningandDebuggingRulesforif-statementsRulesforLoopsTipsforDebuggingHomework

Exercise37SymbolReview

KeywordsDataTypesStringEscapeSequencesOldStyleStringFormatsOperatorsReadingCodeStudyDrillsCommonStudentQuestions

Exercise38DoingThingstoListsWhatYouShouldSeeWhatListsCanDoWhentoUseListsStudyDrillsCommonStudentQuestions

Exercise39DictionariesOhLovelyDictionariesADictionaryExampleWhatYouShouldSeeWhatDictionariesCanDoStudyDrillsCommonStudentQuestions

Exercise40ModulesClassesandObjectsModulesAreLikeDictionaries

ClassesAreLikeModulesObjectsAreLikeImportGettingThingsfromThingsAFirstClassExample

WhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise41LearningtoSpeakObject-OrientedWordDrillsPhraseDrillsCombinedDrillsAReadingTestPracticeEnglishtoCodeReadingMoreCodeCommonStudentQuestions

Exercise42Is-AHas-AObjectsandClassesHowThisLooksinCodeAboutclassName(object)StudyDrillsCommonStudentQuestions

Exercise43BasicObject-OrientedAnalysisandDesignTheAnalysisofaSimpleGameEngine

WriteorDrawAbouttheProblemExtractKeyConceptsandResearchThemCreateaClassHierarchyandObjectMapfortheConceptsCodetheClassesandaTesttoRunThemRepeatandRefine

TopDownversusBottomUpTheCodeforldquoGothonsfromPlanetPercal25rdquoWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise44InheritanceversusCompositionWhatIsInheritance

ImplicitInheritanceOverrideExplicitlyAlterBeforeorAfter

AllThreeCombinedTheReasonforsuper()

Usingsuper()with__init__CompositionWhentoUseInheritanceorCompositionStudyDrillsCommonStudentQuestions

Exercise45YouMakeaGameEvaluatingYourGameFunctionStyleClassStyleCodeStyleGoodCommentsEvaluateYourGame

Exercise46AProjectSkeletonmacOSLinuxSetupWindows10SetupCreatingtheSkeletonProjectDirectory

FinalDirectoryStructureTestingYourSetupUsingtheSkeletonRequiredQuizCommonStudentQuestions

Exercise47AutomatedTestingWritingaTestCaseTestingGuidelinesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise48AdvancedUserInputOurGameLexicon

BreakingUpaSentenceLexiconTuplesScanningInputExceptionsandNumbers

ATestFirstChallengeWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise49MakingSentencesMatchandPeekTheSentenceGrammarAWordonExceptionsTheParserCodePlayingwiththeParserWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise50YourFirstWebsiteInstallingflaskMakeaSimpleldquoHelloWorldrdquoProjectWhatrsquosGoingOnFixingErrorsCreateBasicTemplatesStudyDrillsCommonStudentQuestions

Exercise51GettingInputfromaBrowserHowtheWebWorksHowFormsWork

CreatingHTMLFormsCreatingaLayoutTemplateWritingAutomatedTestsforFormsStudyDrillsBreakingIt

Exercise52TheStartofYourWebGameRefactoringtheExercise43GameCreatinganEngineYourFinalExamCommonStudentQuestions

NextStepsHowtoLearnAnyProgrammingLanguage

AdvicefromanOldProgrammer

AppendixCommandLineCrashCourseIntroductionShutUpandShell

HowtoUseThisAppendixYouWillBeMemorizingThings

TheSetupDoThisYouLearnedThisDoMore

PathsFoldersDirectories(pwd)DoThisYouLearnedThisDoMore

IfYouGetLostDoThisYouLearnedThis

MakeaDirectory(mkdir)DoThis

YouLearnedThisDoMore

ChangeDirectory(cd)DoThisYouLearnedThisDoMore

ListDirectory(ls)DoThisYouLearnedThisDoMore

RemoveDirectory(rmdir)DoThisYouLearnedThisDoMore

MovingAround(pushdpopd)DoThisYouLearnedThisDoMore

MakingEmptyFiles(touchNew-Item)DoThisYouLearnedThisDoMore

CopyaFile(cp)DoThisYouLearnedThisDoMore

MovingaFile(mv)DoThisYouLearnedThisDoMore

ViewaFile(lessmore)

DoThisYouLearnedThisDoMore

StreamaFile(cat)DoThisYouLearnedThisDoMore

RemovingaFile(rm)DoThisYouLearnedThisDoMore

ExitingYourTerminal(exit)DoThisYouLearnedThisDoMore

CommandLineNextStepsUnixBashReferencesPowerShellReferences

Index

Preface

ThissimplebookismeanttogetyoustartedinprogrammingThetitlesaysitrsquosthehardwaytolearntowritecodebutitrsquosactuallynotItrsquosonlytheldquohardrdquowaybecauseitusesatechniquecalledinstructionInstructioniswhereItellyoutodoasequenceofcontrolledexercisesdesignedtobuildaskillthroughrepetitionThistechniqueworksverywellwithbeginnerswhoknownothingandneedtoacquirebasicskillsbeforetheycanunderstandmorecomplextopicsItrsquosusedineverythingfrommartialartstomusictoevenbasicmathandreadingskillsThisbookinstructsyouinPythonbyslowlybuildingandestablishingskillsthroughtechniquessuchaspracticeandmemorizationthenapplyingthemtoincreasinglydifficultproblemsBytheendofthebookyouwillhavethetoolsneededtobeginlearningmorecomplexprogrammingtopicsIliketotellpeoplethatmybookgivesyouyourldquoprogrammingblackbeltrdquoWhatthismeansisthatyouknowthebasicswellenoughtonowstartlearningprogrammingIfyouworkhardtakeyourtimeandbuildtheseskillsyouwilllearntocode

ImprovementsinthePython3EditionLearnPython3theHardWaynowusesPython36IrsquovestandardizedonthisversionofPythonbecauseithasanewimprovedstringformattingsystemthatiseasiertousethantheprevious4(or3Iforgetthereweremany)versionsThereareafewproblemswithPython36forbeginnersbutIhelpyounavigatetheseissuesinthebookAparticularlyhairyproblemisthatPython36hasverypoorerrormessagesinsomekeyareasthatIhelpyouunderstandIhavealsoimprovedthevideosbasedonmyexperiencesoverthelastfiveyearsteachingpeoplePythonYoucanwatchthesevideosonlineatinformitcomtitle9780134692883InthepastthevideossimplyletyouwatchmedotheexerciseThePython3editionvideosalsoshowyouhowtobreakmdashandthenfixmdasheveryexerciseThisskilliscalledldquodebuggingrdquoItteachesyouhowtofixproblemsyourunintobutalsohowPythonrunstheprogramsyoursquorecreatingThegoalofthisnewmethodologyistobuildamentalmodelofhowPythonrunsyourcodesoyoucanmoreeasilyfigureoutwhyitrsquosbrokenYoursquollalsolearnmanyusefultricksfordebuggingbrokensoftwareLastthePython3editionfullysupportsMicrosoftWindows10frombeginningtoendThepreviouseditionfocusedmostlyontheUnix-stylesystemssuchasmacOSandLinuxwithWindowsbeingmoreofanafterthoughtAtthetimeIstartedwritingthePython3editionMicrosofthadstartedtotakeopensource

startedwritingthePython3editionMicrosofthadstartedtotakeopensourcetoolsanddevelopersseriouslyanditwasdifficulttoignorethemasaseriousPythondevelopmentplatformThevideosfeatureMicrosoftWindowsusingPythoninvariousscenariosandalsoshowmacOSandLinuxforfullcompatibilityItellyouaboutanygotchasoneachplatformcoverinstallationinstructionsandprovideanyothertipsIcangiveyou

TheHardWayIsEasierWiththehelpofthisbookyouwilldotheincrediblysimplethingsthatallprogrammersdotolearnaprogramminglanguage

1Gothrougheachexercise2Typeineachfileexactly3Makeitrun

ThatrsquositThiswillbeverydifficultatfirstbutstickwithitIfyougothroughthisbookanddoeachexerciseforoneortwohoursanightyouwillhaveagoodfoundationformovingontoanotherbookaboutPythontocontinueyourstudiesThisbookwonrsquotturnyouintoaprogrammerovernightbutitwillgetyoustartedonthepathtolearninghowtocodeThisbookrsquosjobistoteachyouthethreemostessentialskillsthatabeginningprogrammerneedstoknowreadingandwritingattentiontodetailandspottingdifferences

ReadingandWritingIfyouhaveaproblemtypingyouwillhaveaproblemlearningtocodeespeciallyifyouhaveaproblemtypingthefairlyoddcharactersinsourcecodeWithoutthissimpleskillyouwillbeunabletolearneventhemostbasicthingsabouthowsoftwareworksTypingthecodesamplesandgettingthemtorunwillhelpyoulearnthenamesofthesymbolsgetfamiliarwithtypingthemandgetyoureadingthelanguage

AttentiontoDetailTheoneskillthatseparatesgoodprogrammersfrombadprogrammersisattentiontodetailInfactitrsquoswhatseparatesthegoodfromthebadinanyprofessionYoumustpayattentiontothetiniestdetailsofyourworkoryouwillmissimportantelementsofwhatyoucreateInprogrammingthisishowyouendupwithbugsanddifficult-to-usesystemsBygoingthroughthisbookandcopyingeachexampleexactlyyouwillbetrainingyourbraintofocusonthedetailsofwhatyouaredoingasyouare

doingit

SpottingDifferencesAveryimportantskill(thatmostprogrammersdevelopovertime)istheabilitytovisuallynoticedifferencesbetweenthingsAnexperiencedprogrammercantaketwopiecesofcodethatareslightlydifferentandimmediatelystartpointingoutthedifferencesProgrammershaveinventedtoolstomakethiseveneasierbutwewonrsquotbeusinganyoftheseYoufirsthavetotrainyourbrainthehardwaythenusethetoolsWhileyoudotheseexercisestypingeachoneinyouwillmakemistakesItrsquosinevitableevenseasonedprogrammerswouldmakeafewYourjobistocomparewhatyouhavewrittentowhatrsquosrequiredandfixallthedifferencesBydoingsoyouwilltrainyourselftonoticemistakesbugsandotherproblems

AskDonrsquotStareIfyouwritecodeyouwillwritebugsAldquobugrdquomeansadefecterrororproblemwiththecodeyoursquovewrittenThelegendssaythatthiscomesfromanactualmoththatflewintooneofthefirstcomputerscausingittomalfunctionFixingitrequiredldquodebuggingrdquothecomputerIntheworldofsoftwaretherearealotofbugsSomanyLikethatfirstmothyourbugswillbehiddensomewhereinthecodeandyouhavetogofindthemYoucanrsquotjustsitatyourcomputerscreenstaringatthewordsyoursquovewrittenhopingthattheanswerjumpsoutatyouThereisnomoreadditionalinformationyoucangetdoingthatandyouneedadditionalinformationYouneedtogetupandgofindthemothTodothatyouhavetointerrogateyourcodeandaskitwhatisgoingonorlookattheproblemfromadifferentviewInthisbookIfrequentlytellyoutoldquostopstaringandaskrdquoIshowyouhowtomakeyourcodetellyoueverythingitcanaboutwhatrsquosgoingonandhowtoturnthisintopossiblesolutionsIalsoshowyouhowtoseeyourcodeindifferentwayssoyoucangetmoreinformationandinsight

DoNotCopy-PasteYoumusttypeeachoftheseexercisesinmanuallyIfyoucopy-pasteyoumightaswellnotevendothemThepointoftheseexercisesistotrainyourhandsyourbrainandyourmindinhowtoreadwriteandseecodeIfyoucopy-pasteyouarecheatingyourselfoutoftheeffectivenessofthelessons

UsingtheIncludedVideos

LearnPython3theHardWayhasanextensivesetofvideosdemonstratinghowthecodeworksandmostimportantlyhowtobreakitThevideosaretheperfectplacetodemonstratemanycommonerrorsbybreakingthePythoncodeonpurposeandshowingyouhowtofixitIalsowalkthroughthecodeusingdebuggingandinterrogationtricksandtechniquesThevideosarewhereIshowyouhowtoldquostopstaringandaskrdquothecodewhatrsquoswrongYoucanwatchthesevideosonlineatinformitcomtitle9780134692883

ANoteonPracticeandPersistenceWhileyouarestudyingprogrammingIrsquomstudyinghowtoplayguitarIpracticeiteverydayforatleasttwohoursadayIplayscaleschordsandarpeggiosforanhourandthenlearnmusictheoryeartrainingsongsandanythingelseIcanSomedaysIstudyguitarandmusicforeighthoursbecauseIfeellikeitanditrsquosfunTomerepetitivepracticeisnaturalandjusthowtolearnsomethingIknowthattogetgoodatanythingIhavetopracticeeverydayevenifIsuckthatday(whichisoften)oritrsquosdifficultKeeptryingandeventuallyitrsquollbeeasierandfunBetweenthetimethatIwroteLearnPythontheHardWayandLearnRubytheHardWayIdiscovereddrawingandpaintingIfellinlovewithmakingvisualartattheageof39andhavebeenspendingeverydaystudyingitinmuchthesamewaythatIstudiedguitarmusicandprogrammingIcollectedbooksofinstructionalmaterialdidwhatthebookssaidpaintedeverydayandfocusedonenjoyingtheprocessoflearningIambynomeansanldquoartistrdquooreventhatgoodbutIcannowsaythatIcandrawandpaintThesamemethodIrsquomteachingyouinthisbookappliedtomyadventuresinartIfyoubreaktheproblemdownintosmallexercisesandlessonsanddothemeverydayyoucanlearntodoalmostanythingIfyoufocusonslowlyimprovingandenjoyingthelearningprocessthenyouwillbenefitnomatterhowgoodyouareatitAsyoustudythisbookandcontinuewithprogrammingrememberthatanythingworthdoingisdifficultatfirstMaybeyouarethekindofpersonwhoisafraidoffailuresoyougiveupatthefirstsignofdifficultyMaybeyouneverlearnedself-disciplinesoyoucanrsquotdoanythingthatrsquosldquoboringrdquoMaybeyouweretoldthatyouareldquogiftedrdquosoyouneverattemptanythingthatmightmakeyouseemstupidornotaprodigyMaybeyouarecompetitiveandunfairlycompareyourselftosomeonelikemewhorsquosbeenprogrammingformorethan20yearsWhateveryourreasonforwantingtoquitkeepatitForceyourselfIfyourunintoaStudyDrillyoucanrsquotdooralessonyoujustdonotunderstandthenskip

itandcomebacktoitlaterJustkeepgoingbecausewithprogrammingtherersquosthisveryoddthingthathappensAtfirstyouwillnotunderstandanythingItrsquollbeweirdjustlikewithlearninganyhumanlanguageYouwillstrugglewithwordsandnotknowwhatsymbolsarewhatanditrsquollallbeveryconfusingThenonedayBANGmdashyourbrainwillsnapandyouwillsuddenlyldquogetitrdquoIfyoukeepdoingtheexercisesandkeeptryingtounderstandthemyouwillgetitYoumightnotbeamastercoderbutyouwillatleastunderstandhowprogrammingworksIfyougiveupyouwonrsquoteverreachthispointYouwillhitthefirstconfusingthing(whichiseverythingatfirst)andthenstopIfyoukeeptryingkeeptypingitinkeeptryingtounderstanditandreadingaboutityouwilleventuallygetitIfyougothroughthiswholebookandyoustilldonotunderstandhowtocodeatleastyougaveitashotYoucansayyoutriedyourbestandalittlemoreanditdidnrsquotworkoutbutatleastyoutriedYoucanbeproudofthat

RegisteryourcopyofLearnPython3theHardWayontheInformITsiteforconvenientaccesstoupdatesandcorrectionsastheybecomeavailableTostarttheregistrationprocessgotoinformitcomregisterandloginorcreateanaccountEntertheproductISBN(9780134692883)andanswerthesimpleproof-of-purchasequestionThenlookontheRegisteredProductstabforanAccessBonusContentlinknexttothisproductandfollowthatlinktoaccessthebonusmaterials

AcknowledgmentsIwouldliketothankAngelaforhelpingmewiththefirsttwoversionsofthisbookWithoutherIprobablywouldnrsquothavebotheredtofinishitatallShedidthecopyeditingofthefirstdraftandsupportedmeimmenselywhileIwroteitIrsquodalsoliketothankGregNewmanfordoingtheoriginalcoverartBrianShumateforearlywebsitedesignsandallofthepeoplewhoreadthisbookandtookthetimetosendmefeedbackandcorrectionsThankyou

Exercise0TheSetup

ThisexercisehasnocodeItissimplytheexerciseyoucompletetogetyourcomputertorunPythonYoushouldfollowtheseinstructionsasexactlyaspossibleIfyouhaveproblemsfollowingthewritteninstructionsthenwatchtheincludedvideosforyourplatform

WarningIfyoudonotknowhowtousePowerShellonWindowsTerminalonmacOSorbashonLinuxthenyouneedtogolearnthatfirstYoushoulddotheexercisesintheappendixfirstbeforecontinuingwiththeseexercises

macOSDothefollowingtaskstocompletethisexercise

1Gotohttpswwwpythonorgdownloadsreleasepython-360anddownloadtheversiontitledldquoMacOSX64-bit32-bitinstallerrdquoInstallitlikeyouwouldanyothersoftware

2GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3PutAtom(yourtexteditor)inyourdocksoyoucanreachiteasily4FindyourTerminalprogramSearchforitYouwillfindit5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthenameandhittingRETURN

8Typequit()Enterandgetoutofpython369YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryintheTerminal11LearnhowtochangeintoadirectoryintheTerminal12UseyoureditortocreateafileinthisdirectoryMakethefileSaveor

SaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindows14BackinTerminallistthedirectorywithlstoseeyournewlycreatedfile

macOSWhatYouShouldSeeHerersquosmedoingthisonmymacOScomputerinTerminalYourcomputermightbedifferentbutshouldbesimilartothisClickheretoviewcodeimage

$python36

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clangndash700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgt

~$mkdirlpthw

~$cdlpthw

lpthw$ls

Useyourtexteditorheretoedittesttxt

lpthw$ls

testtxt

lpthw$

Windows1GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitYoudonotneedtobetheadministratortodothis

2MakesureyoucangettoAtomeasilybyputtingitonyourdesktopandorinQuickLaunchBothoptionsareavailableduringsetupIfyoucannotrunAtombecauseyourcomputerisnotfastenoughthenseetheAlternativeTextEditorssectionattheendofthisexercise

3RunPowerShellfromtheStartmenuSearchforitandjustpressEntertorunit

4MakeashortcuttoitonyourdesktopandorQuickLaunchforyourconvenience

5RunyourPowerShellprogram(whichIwillcallTerminallater)Itwonrsquotlooklikemuch

6DownloadPython36fromhttpswwwpythonorgdownloadsreleasepython-360andinstallitBesuretochecktheboxthatsaystoaddPython36toyourpath

7InyourPowerShell(Terminal)programrunpythonYourunthingsinTerminalbyjusttypingthenameandpressingEnterIfyoutypepythonanditdoesnotrunthenyouhavetoreinstallPythonandmakesureyouchecktheboxforldquoAddpythontothePATHrdquoItrsquosverysmallsolookcarefully

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinthePowerShell(Terminal)11LearnhowtochangeintoadirectoryinthePowerShell(Terminal)12UseyoureditortocreateafileinthisdirectoryMakethefileSaveorSaveAsandpickthisdirectory

13GobacktoPowerShell(Terminal)usingjustthekeyboardtoswitchwindowsLookitupifyoucanrsquotfigureitout

14BackinPowerShell(Terminal)listthedirectorytoseeyournewlycreatedfile

FromnowonwhenIsayldquoTerminalrdquoorldquoshellrdquoImeanPowerShellandthatrsquoswhatyoushoulduseWhenIrunpython36youcanjusttypepython

WindowsWhatYouShouldSeeClickheretoviewcodeimage

gtpython

gtgtgtquit()

gtmkdirlpthw

gtcdlpthw

Hereyouwoulduseyourtexteditortomaketesttxtinlpthw

gt

gtdir

VolumeindriveCis

VolumeSerialNumberis085C-7E02

DirectoryofCDocumentsandSettingsyoulpthw

040520102332ltDIRgt

040520102332ltDIRgt

0405201023326testtxt

1File(s)6bytes

2Dir(s)14804623360bytesfree

gt

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

LinuxLinuxisavariedoperatingsystemwithmanydifferentwaystoinstallsoftwareIrsquomassumingifyouarerunningLinuxthenyouknowhowtoinstallpackagessohereareyourinstructions

1UseyourpackagemanagertoinstallPython36andifyoucanrsquotthendownloadsourcefromhttpswwwpythonorgdownloadsreleasepython-360andbuildfromsource

2UseyourLinuxpackagemanagerandinstalltheAtomtexteditorIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3MakesureyoucangettoAtomeasilybyputtingitinyourwindowmanagerrsquosmenu

4FindyourTerminalprogramItcouldbecalledGNOMETerminalKonsoleorxterm

5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthecommandnameandpressingEnterIfyoucanrsquotrunpython36tryrunningjustpython

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinTerminal11LearnhowtochangeintoadirectoryinTerminal12UseyoureditortocreateafileinthisdirectoryTypicallyyouwillmake

thefileSaveorSaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindowsLookit

upifyoucanrsquotfigureitout14BackinTerminallistthedirectorytoseeyournewlycreatedfile

LinuxWhatYouShouldSee

Clickheretoviewcodeimage

$python

gtgtgtquit()

$mkdirlpthw

$cdlpthw

Useyourtexteditorheretoedittesttxt

$ls

testtxt

$

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

FindingThingsontheInternetAmajorpartofthisbookislearningtoresearchprogrammingtopicsonlineIrsquolltellyoutoldquosearchforthisontheinternetrdquoandyourjobistouseasearchenginetofindtheanswerThereasonIhaveyousearchinsteadofjustgivingyoutheanswerisbecauseIwantyoutobeanindependentlearnerwhodoesnotneedmybookwhenyoursquoredonewithitIfyoucanfindtheanswerstoyourquestionsonlinethenyouareonestepclosertonotneedingmeandthatismygoalThankstosearchenginessuchasGoogleyoucaneasilyfindanythingItellyoutofindIfIsayldquosearchonlineforthepythonlistfunctionsrdquothenyousimplydothis

1Gotohttpgooglecom2Typepython3listfunctions3Readthewebsiteslistedtofindthebestanswer

WarningsforBeginnersYouaredonewiththisexerciseThisexercisemightbehardforyoudependingonyourfamiliaritywithyourcomputerIfitisdifficulttakethetimetoreadandstudyandgetthroughitbecauseuntilyoucandotheseverybasicthingsyouwillfinditdifficulttogetmuchprogrammingdoneIfsomeonetellsyoutostopataspecificexerciseinthisbookortoskipcertainonesyoushouldignorethatpersonAnyonetryingtohideknowledgefromyouorworsemakeyougetitfromtheminsteadofthroughyourowneffortsistryingtomakeyoudependonthemforyourskillsDonrsquotlistentothemanddotheexercisesanywaysothatyoulearnhowtoeducateyourselfAprogrammerwilleventuallytellyoutousemacOSorLinuxIftheprogrammerlikesfontsandtypographytheyrsquolltellyoutogetamacOScomputerIfhelikescontrolandhasahugebeardhewill(orzewillifyou

computerIfhelikescontrolandhasahugebeardhewill(orzewillifyouprefernon-genderedpronounsforhumanswithbeards)tellyoutoinstallLinuxAgainusewhatevercomputeryouhaverightnowthatworksAllyouneedisaneditoraTerminalandPythonFinallythepurposeofthissetuphelpsyoudothreethingsveryreliablywhileyouworkontheexercises

1Writeexercisesusingthetexteditor2Runtheexercisesyouwrote3Fixthemwhentheyarebroken4Repeat

Anythingelsewillonlyconfuseyousosticktotheplan

AlternativeTextEditorsTexteditorsareveryimportanttoaprogrammerbutasabeginneryouonlyneedasimpleprogrammerrsquostexteditorThesearedifferentfromsoftwareforwritingstoriesandbooksbecausetheyworkwiththeuniqueneedsofcomputercodeIrecommendAtominthisbookbecauseitisfreeandworksnearlyeverywhereHoweverAtommaynotrunwellonyourcomputersoherearesomealternativestotry

ThesearerankedinorderofmostlikelytoworkKeepinmindthattheseprojectsmaybeabandoneddeadornotworkanymoreonyourcomputerIfyoutryoneanditdoesnrsquotworktryanotheroneIrsquovealsolistedtheldquoWorksOnrdquoinorderofmostlikelytoworksoifyoursquoreonWindowsthenlookattheeditorswhereWindowsislistedfirstintheldquoWorksOnrdquocolumnIfyoualreadyknowhowtouseVimorEmacsthenfeelfreetousethemIfyouhaveneverusedVimorEmacsthenavoidthemProgrammersmaytrytoconvinceyoutouseVimorEmacsbutthiswillonlyderailyouYourfocusislearningPythonnotlearningVimorEmacsIfyoutrytouseVimanddonrsquotknowhowtoquitthentypeqorZZIfsomeonetoldyoutouseVimand

theydidnrsquoteventellyouthisthennowyouknowwhyyoushouldnrsquotlistentothemDonotuseanIntegratedDevelopmentEnvironment(IDE)whileyougothroughthisbookRelyingonanIDEmeansthatyoucanrsquotworkwithnewprogramminglanguagesuntilsomecompanydecidestosellyouanIDEforthatlanguageThismeansyoucanrsquotusethatnewlanguageuntilthelanguageislargeenoughtojustifyalucrativecustomerbaseIfyouareconfidentyoucanworkwithonlyaprogrammerrsquostexteditor(likeVimEmacsAtometc)thenyoudonrsquothavetowaitforathirdpartyIDEsareniceinsomesituations(suchasworkingwithagiantexistingcodebase)butbeingaddictedtothemwilllimityourfutureYoushouldalsonotuseIDLEIthasseriouslimitationsinhowitworksandisnrsquotaverygoodpieceofsoftwareAllyouneedisasimpletexteditorashellandPython

Exercise1AGoodFirstProgram

WarningIfyouskippedExercise0thenyouarenotdoingthisbookrightAreyoutryingtouseIDLEoranIDEIsaidnottouseoneinExercise0soyoushouldnotuseoneIfyouskippedExercise0pleasegobacktoitandreadit

YoushouldhavespentagoodamountoftimeinExercise0learninghowtoinstallatexteditorrunthetexteditorruntheTerminalandworkwithbothofthemIfyouhavenrsquotdonethatthendonotgoonYouwillnothaveagoodtimeThisistheonlytimeIrsquollstartanexercisewithawarningthatyoushouldnotskiporgetaheadofyourselfTypethefollowingtextintoasinglefilenamedex1pyPythonworksbestwithfilesendinginpyClickheretoviewcodeimage

ex1py

1print(HelloWorld)

2print(HelloAgain)

3print(Iliketypingthis)

4print(Thisisfun)

5print(YayPrinting)

6print(Idmuchratheryounot)

7print(Isaiddonottouchthis)

YourAtomtexteditorshouldlooksomethinglikethisonallplatforms

DonrsquotworryifyoureditordoesnrsquotlookexactlythesameitshouldbeclosethoughYoumayhaveaslightlydifferentwindowheadermaybeslightlydifferentcolorsandtheleftsideofyourAtomwindowwonrsquotsayldquozedshawrdquobutwillinsteadshowthedirectoryyouusedforsavingyourfilesAllofthosedifferencesarefineWhenyoucreatethisfilekeepinmindthesepoints

1IdidnottypethelinenumbersontheleftThoseareprintedinthebooksoIcantalkaboutspecificlinesbysayingldquoSeeline5rdquoYoudonottypelinenumbersintoPythonscripts

2IhavetheprintatthebeginningofthelineanditlooksexactlythesameaswhatIhaveinex1pyExactlymeansexactlynotkindofsortofthesameEverysinglecharacterhastomatchforittoworkColordoesnrsquot

matteronlythecharactersyoutypeInmacOSTerminalor(maybe)Linuxrunthefilebytyping

python36ex1py

OnWindowsrememberyoualwaystypepythoninsteadofpython36likethis

pythonex1py

IfyoudiditrightthenyoushouldseethesameoutputasIintheWhatYouShouldSeesectionofthisexerciseIfnotyouhavedonesomethingwrongNothecomputerisnotwrong

WhatYouShouldSeeOnmacOSintheTerminalyoushouldseethis

OnWindowsinPowerShellyoushouldseethis

Youmayseedifferentnamesbeforethepython36ex1pycommandbuttheimportantpartisthatyoutypethecommandandseetheoutputisthesameasmineIfyouhaveanerroritwilllooklikethisClickheretoviewcodeimage

$python36pythonex1py

Filepythonex1pyline3

print(Iliketypingthis

^

SyntaxErrorEOLwhilescanningstringliteral

ItrsquosimportantthatyoucanreadtheseerrormessagesbecauseyouwillbemakingmanyofthesemistakesEvenImakemanyofthesemistakesLetrsquoslookatthislinebyline

1WeranourcommandintheTerminaltoruntheex1pyscript2Pythontellsusthatthefileex1pyhasanerroronline3ofex1py3Itprintsthislineofcodeforustoseeit4Thenitputsa^(caret)charactertopointatwheretheproblemisNoticethemissing(double-quote)character

5FinallyitprintsoutaldquoSyntaxErrorrdquoandtellsussomethingaboutwhatmightbetheerrorUsuallytheseareverycrypticbutifyoucopythattext

mightbetheerrorUsuallytheseareverycrypticbutifyoucopythattextintoasearchengineyouwillfindsomeoneelsewhorsquoshadthaterrorandyoucanprobablyfigureouthowtofixit

StudyDrillsTheStudyDrillscontainthingsyoushouldtrytodoIfyoucanrsquotskipitandcomebacklaterForthisexercisetrythesethings

1Makeyourscriptprintanotherline2Makeyourscriptprintonlyoneofthelines3Puta(octothorpe)characteratthebeginningofalineWhatdiditdoTrytofindoutwhatthischaracterdoes

FromnowonIwonrsquotexplainhoweachexerciseworksunlessanexerciseisdifferent

WarningAnldquooctothorperdquoisalsocalledaldquopoundrdquoldquohashrdquoldquomeshrdquooranynumberofothernamesPicktheonethatmakesyouchillout

CommonStudentQuestionsTheseareactualquestionsthatrealstudentshaveaskedwhendoingthisexercise

CanIuseIDLENoyoushoulduseTerminalonmacOSandPowerShellonWindowsjustlikeIhavehereIfyoudonrsquotknowhowtousethosethenyoucangoreadtheappendix

HowdoyougetcolorsinyoureditorSaveyourfilefirstasapyfilesuchasex1pyThenyoursquollhavecolorwhenyoutype

IgetSyntaxErrorinvalidsyntaxwhenIrunex1pyYouareprobablytryingtorunPythonthentryingtotypePythonagainCloseyourTerminalstartitagainandrightawaytypeonlypython36ex1py

Igetcantopenfileex1py[Errno2]NosuchfileordirectoryYouneedtobeinthesamedirectoryasthefileyoucreatedMakesureyouusethecdcommandtogotherefirstForexampleifyousavedyourfileinlpthwex1pythenyouwoulddocdlpthwbeforetryingtorunpython36

ex1pyIfyoudonrsquotknowwhatanyofthatmeansthengothroughtheappendix

MyfiledoesnrsquotrunIjustgetthepromptbackwithnooutputYoumostlikelytookthecodeinmyex1pyfileliterallyandthoughtthatprint(HelloWorld)meanttotypeonlyHelloWorldintothefilewithouttheprintYourfilehastobeexactlylikemine

Exercise2CommentsandPoundCharacters

CommentsareveryimportantinyourprogramsTheyareusedtotellyouwhatsomethingdoesinEnglishandtheyareusedtodisablepartsofyourprogramifyouneedtoremovethemtemporarilyHerersquoshowyouusecommentsinPythonClickheretoviewcodeimage

ex2py

1Acommentthisissoyoucanreadyourprogramlater

2Anythingaftertheisignoredbypython

3

4print(Icouldhavecodelikethis)andthecommentafteris

ignored

5

6Youcanalsouseacommenttodisableorcommentoutcode

7print(Thiswontrun)

8

9print(Thiswillrun)

FromnowonIrsquomgoingtowritecodelikethisItisimportantforyoutounderstandthateverythingdoesnothavetobeliteralYourscreenandprogrammayvisuallylookdifferentbutwhatrsquosimportantisthetextyoutypeintothefileyoursquorewritinginyourtexteditorInfactIcouldworkwithanytexteditorandtheresultswouldbethesame

WhatYouShouldSee

Exercise2Session

$python36ex2py

Icouldhavecodelikethis

Thiswillrun

AgainIrsquomnotgoingtoshowyouscreenshotsofalltheTerminalspossibleYoushouldunderstandthattheprecedingisnotaliteraltranslationofwhatyouroutputshouldlooklikevisuallybutthetextbetweenthefirst$python36andlast$lineswillbewhatyoufocuson

StudyDrills

1Findoutifyouwererightaboutwhatthecharacterdoesandmakesureyouknowwhatitrsquoscalled(octothorpeorpoundcharacter)

2Takeyourex2pyfileandrevieweachlinegoingbackwardStartatthelastlineandcheckeachwordinreverseagainstwhatyoushouldhavetyped

3DidyoufindmoremistakesFixthem4ReadwhatyoutypedaboveoutloudincludingsayingeachcharacterbyitsnameDidyoufindmoremistakesFixthem

CommonStudentQuestionsAreyousureiscalledthepoundcharacterIcallittheoctothorpebecausethatistheonlynamethatnoonecountryusesandthatworksineverycountryEverycountrythinksitsnameforthisonecharacterisboththemostimportantwaytodoitandtheonlywayitrsquosdoneTomethisissimplyarroganceandreallyyrsquoallshouldjustchilloutandfocusonmoreimportantthingslikelearningtocode

Whydoestheinprint(Hithere)notgetignoredTheinthatcodeisinsideastringsoitwillbeputintothestringuntiltheendingcharacterishitPoundcharactersinstringsarejustconsideredcharactersnotcomments

HowdoIcommentoutmultiplelinesPutainfrontofeachoneIcanrsquotfigureouthowtotypeacharacteronmycountryrsquoskeyboardHowdoIdothatSomecountriesusetheALTkeyandcombinationsofotherkeystoprintcharactersforeigntotheirlanguageYoursquollhavetolookonlineinasearchenginetoseehowtotypeit

WhydoIhavetoreadcodebackwardItrsquosatricktomakeyourbrainnotattachmeaningtoeachpartofthecodeanddoingthatmakesyouprocesseachpieceexactlyThisisahandyerror-checkingtechnique

Exercise3NumbersandMath

EveryprogramminglanguagehassomekindofwayofdoingnumbersandmathDonotworryprogrammersfrequentlylieaboutbeingmathgeniuseswhentheyreallyarenrsquotIftheyweremathgeniusestheywouldbedoingmathnotwritingbuggywebframeworkssotheycandriveracecarsThisexercisehaslotsofmathsymbolsLetrsquosnamethemrightawaysoyouknowwhattheyarecalledAsyoutypethisoneinsaythenameWhensayingthemfeelsboringyoucanstopsayingthemHerearethenamesbull+plusbull-minusbullslashbullasteriskbullpercentbullltless-thanbullgtgreater-thanbulllt=less-than-equalbullgt=greater-than-equalNoticehowtheoperationsaremissingAfteryoutypeinthecodeforthisexercisegobackandfigureoutwhateachofthesedoesandcompletethetableForexample+doesadditionClickheretoviewcodeimage

ex3py

1print(Iwillnowcountmychickens)

2

3print(Hens25+306)

4print(Roosters100-2534)

5

6print(NowIwillcounttheeggs)

7

8print(3+2+1-5+42-14+6)

9

10print(Isittruethat3+2lt5-7)

11

12print(3+2lt5-7)

13

14print(Whatis3+23+2)

15print(Whatis5-75-7)

16

17print(OhthatswhyitsFalse)

18

19print(Howaboutsomemore)

20

21print(Isitgreater5gt-2)

22print(Isitgreaterorequal5gt=-2)

23print(Isitlessorequal5lt=-2)Makesureyoutypethis

exactlybeforeyourunitCompareeachlineofyourfiletomyfile

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise3Session

$python36ex3py

Iwillnowcountmychickens

Hens300

Roosters97

NowIwillcounttheeggs

675

Isittruethat3+2lt5-7

False

Whatis3+25

Whatis5-7-2

OhthatswhyitsFalse

Howaboutsomemore

IsitgreaterTrue

IsitgreaterorequalTrue

IsitlessorequalFalse

StudyDrills1Aboveeachlineusethetowriteacommenttoyourselfexplainingwhatthelinedoes

2RememberinExercise0whenyoustartedpython36Startpython36thiswayagainandusingthemathoperatorsusePythonasacalculator

3Findsomethingyouneedtocalculateandwriteanewpyfilethatdoesit

4Rewriteex3pytousefloatingpointnumberssoitrsquosmoreaccurate200isfloatingpoint

CommonStudentQuestionsWhyisthecharacteraldquomodulusrdquoandnotaldquopercentrdquoMostlythatrsquosjusthowthedesignerschosetousethatsymbolInnormalwritingyouarecorrecttoreaditasaldquopercentrdquoInprogrammingthiscalculationistypicallydonewithsimpledivisionandtheoperatorThemodulusisadifferentoperationthatjusthappenstousethesymbol

HowdoesworkAnotherwaytosayitisldquoXdividedbyYwithJ

remainingrdquoForexampleldquo100dividedby16with4remainingrdquoTheresultofistheJpartortheremainingpart

WhatistheorderofoperationsIntheUnitedStatesweuseanacronymcalledPEMDASwhichstandsforParenthesesExponentsMultiplicationDivisionAdditionSubtractionThatrsquostheorderPythonfollowsaswellThemistakepeoplemakewithPEMDASistothinkthisisastrictorderasinldquoDoPthenEthenMthenDthenAthenSrdquoTheactualorderisyoudothemultiplicationanddivision(MampD)inonestepfromlefttorightthenyoudotheadditionandsubtractioninonestepfromlefttorightSoyoucouldrewritePEMDASasPE(MampD)(AampS)

Exercise4VariablesandNames

NowyoucanprintthingswithprintandyoucandomathThenextstepistolearnaboutvariablesInprogrammingavariableisnothingmorethananameforsomethingsimilartohowmynameldquoZedrdquoisanameforldquothehumanwhowrotethisbookrdquoProgrammersusethesevariablenamestomaketheircodereadmorelikeEnglishandbecausetheyhavelousymemoriesIftheydidnrsquotusegoodnamesforthingsintheirsoftwaretheyrsquodgetlostwhentheytriedtoreadtheircodeagainIfyougetstuckwiththisexerciserememberthetricksyouhavebeentaughtsofaroffindingdifferencesandfocusingondetails1WriteacommentaboveeachlineexplainingtoyourselfinEnglishwhatitdoes

2Readyourpyfilebackward3Readyourpyfileoutloudsayingeventhecharacters

Clickheretoviewcodeimage

ex4py

1cars=100

2space_in_a_car=40

3drivers=30

4passengers=90

5cars_not_driven=cars-drivers

6cars_driven=drivers

7carpool_capacity=cars_drivenspace_in_a_car

8average_passengers_per_car=passengerscars_driven

9

10

11print(Therearecarscarsavailable)

12print(Thereareonlydriversdriversavailable)

13print(Therewillbecars_not_drivenemptycarstoday)

14print(Wecantransportcarpool_capacitypeopletoday)

15print(Wehavepassengerstocarpooltoday)

16print(Weneedtoputaboutaverage_passengers_per_car

17ineachcar)

WarningThe_inspace_in_a_cariscalledanunderscorecharacterFindouthowtotypeitifyoudonotalreadyknowWeusethischaracteralotto

putanimaginaryspacebetweenwordsinvariablenames

WhatYouShouldSeeClickheretoviewcodeimage

Exercise4Session

$python36ex4py

Thereare100carsavailable

Thereareonly30driversavailable

Therewillbe70emptycarstoday

Wecantransport1200peopletoday

Wehave90tocarpooltoday

Weneedtoputabout30ineachcar

StudyDrillsWhenIwrotethisprogramthefirsttimeIhadamistakeandPythontoldmeaboutitlikethisClickheretoviewcodeimage

Traceback(mostrecentcalllast)

Fileex4pyline8inltmodulegt

average_passengers_per_car=car_pool_capacitypassenger

NameErrornamecar_pool_capacityisnotdefined

ExplainthiserrorinyourownwordsMakesureyouuselinenumbersandexplainwhyHerearemorestudydrills1Iused40forspace_in_a_carbutisthatnecessaryWhathappensifitrsquosjust4

2Rememberthat40isafloatingpointnumberItrsquosjustanumberwithadecimalpointandyouneed40insteadofjust4sothatitisfloatingpoint

3Writecommentsaboveeachofthevariableassignments4Makesureyouknowwhat=iscalled(equals)andthatitspurposeistogivedata(numbersstringsetc)names(cars_drivenpassengers)

5Rememberthat_isanunderscorecharacter6Tryrunningpython36fromtheTerminalasacalculatorlikeyoudidbeforeandusevariablenamestodoyourcalculationsPopularvariablenamesincludeixandj

CommonStudentQuestions

CommonStudentQuestionsWhatisthedifferencebetween=(single-equal)and==(double-equal)The=(single-equal)assignsthevalueontherighttoavariableontheleftThe==(double-equal)testswhethertwothingshavethesamevalueYoursquolllearnaboutthisinExercise27

Canwewritex=100insteadofx=100YoucanbutitrsquosbadformYoushouldaddspacearoundoperatorslikethissothatitrsquoseasiertoread

WhatdoyoumeanbyldquoreadthefilebackwardrdquoVerysimpleImagineyouhaveafilewith16linesofcodeinitStartatline16andcompareittomyfileatline16Thendoitagainfor15andsoonuntilyoursquovereadthewholefilebackward

Whydidyouuse40forspace_in_a_carItismostlysoyoucanthenfindoutwhatafloatingpointnumberisandaskthisquestionSeetheStudyDrills

Exercise5MoreVariablesandPrinting

NowwersquolldoevenmoretypingofvariablesandprintingthemoutThistimewersquollusesomethingcalledaformatstringEverytimeyouput(double-quotes)aroundapieceoftextyouhavebeenmakingastringAstringishowyoumakesomethingthatyourprogrammightgivetoahumanYouprintstringssavestringstofilessendstringstowebserversamongmanyotherthingsStringsarereallyhandysointhisexerciseyouwilllearnhowtomakestringsthathavevariablesembeddedinthemYouembedvariablesinsideastringbyusingaspecialsequenceandthenputthevariableyouwantinsidethecharactersYoualsomuststartthestringwiththeletterfforldquoformatrdquoasinfHellosomevarThislittlefbeforethe(double-quote)andthecharacterstellPython3ldquoHeythisstringneedstobeformattedPutthesevariablesinthererdquoAsusualjusttypethisinevenifyoudonotunderstanditandmakeitexactlythesameClickheretoviewcodeimage

ex5py

1my_name=ZedAShaw

2my_age=35notalie

3my_height=74inches

4my_weight=180lbs

5my_eyes=Blue

6my_teeth=White

7my_hair=Brown

8

9print(fLetstalkaboutmy_name)

10print(fHesmy_heightinchestall)

11print(fHesmy_weightpoundsheavy)

12print(Actuallythatsnottooheavy)

13print(fHesgotmy_eyeseyesandmy_hairhair)

14print(fHisteethareusuallymy_teethdependingonthe

coffee)

15

16thislineistrickytrytogetitexactlyright

17total=my_age+my_height+my_weight

18print(fIfIaddmy_agemy_heightandmy_weightIget

total)

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise5Session

$python36ex5py

LetstalkaboutZedAShaw

Hes74inchestall

Hes180poundsheavy

Actuallythatsnottooheavy

HesgotBlueeyesandBrownhair

HisteethareusuallyWhitedependingonthecoffee

IfIadd3574and180Iget289

StudyDrills1Changeallthevariablessothereisnomy_infrontofeachoneMakesureyouchangethenameeverywherenotjustwhereyouused=tosetthem

2TrytowritesomevariablesthatconverttheinchesandpoundstocentimetersandkilogramsDonotjusttypeinthemeasurementsWorkoutthemathinPython

CommonStudentQuestionsCanImakeavariablelikethis1=ZedShawNo1isnotavalidvariablenameTheyneedtostartwithacharactersoa1wouldworkbut1willnot

HowcanIroundafloatingpointnumberYoucanusetheround()functionlikethisround(17333)

WhydoesthisnotmakesensetomeTrymakingthenumbersinthisscriptyourmeasurementsItrsquosweirdbuttalkingaboutyourselfwillmakeitseemmorerealAlsoyoursquorejuststartingoutsoitwonrsquotmaketoomuchsenseKeepgoingandmoreexerciseswillexplainitmore

Exercise6StringsandText

WhileyouhavebeenwritingstringsyoustilldonotknowwhattheydoInthisexercisewecreateabunchofvariableswithcomplexstringssoyoucanseewhattheyareforFirstanexplanationofstringsAstringisusuallyabitoftextyouwanttodisplaytosomeoneorldquoexportrdquooutoftheprogramyouarewritingPythonknowsyouwantsomethingtobeastringwhenyouputeither(double-quotes)or(single-quotes)aroundthetextYousawthismanytimeswithyouruseofprintwhenyouputthetextyouwanttogoinsidethestringinsideoraftertheprinttoprintthestringStringscancontainanynumberofvariablesthatareinyourPythonscriptRememberthatavariableisanylineofcodewhereyousetaname=(equal)toavalueInthecodeforthisexercisetypes_of_people=10createsavariablenamedtypes_of_peopleandsetsit=(equal)to10Youcanputthatinanystringwithtypes_of_peopleYoualsoseethatIhavetouseaspecialtypeofstringtoldquoformatrdquoitrsquoscalledanldquof-stringrdquoandlookslikethisClickheretoviewcodeimage

fsomestuffhereavariable

fsomeotherstuffanothervar

Pythonalsohasanotherkindofformattingusingtheformat()syntaxwhichyouseeonline17YoursquollseemeusethatsometimeswhenIwanttoapplyaformattoanalready-createdstringsuchasinaloopWersquollcoverthatmorelaterWewillnowtypeinawholebunchofstringsvariablesandformatsandprintthemWewillalsopracticeusingshortabbreviatedvariablenamesProgrammerslovesavingtimeatyourexpensebyusingannoyinglyshortandcrypticvariablenamessoletrsquosgetyoustartedreadingandwritingthemearlyonClickheretoviewcodeimage

ex6py

1types_of_people=10

2x=fTherearetypes_of_peopletypesofpeople

3

4binary=binary

5do_not=dont

6y=fThosewhoknowbinaryandthosewhodo_not

7

8print(x)

9print(y)

10

11print(fIsaidx)

12print(fIalsosaidy)

13

14hilarious=False

15joke_evaluation=Isntthatjokesofunny

16

17print(joke_evaluationformat(hilarious))

18

19w=Thisistheleftsideof

20e=astringwitharightside

21

22print(w+e)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise6Session

$python36ex6py

Thereare10typesofpeople

Thosewhoknowbinaryandthosewhodont

IsaidThereare10typesofpeople

IalsosaidThosewhoknowbinaryandthosewhodont

IsntthatjokesofunnyFalse

Thisistheleftsideofastringwitharightside

StudyDrills1Gothroughthisprogramandwriteacommentaboveeachlineexplainingit

2FindalltheplaceswhereastringisputinsideastringTherearefourplaces

3AreyousurethereareonlyfourplacesHowdoyouknowMaybeIlikelying

4Explainwhyaddingthetwostringswandewith+makesalongerstring

BreakIt

YouarenowatapointwhereyoucantrytobreakyourcodetoseewhathappensThinkofthisasagametodevisethemostcleverwaytobreakthecodeYoucanalsofindthesimplestwaytobreakitOnceyoubreakthecodeyouthenneedtofixitIfyouhaveafriendthenthetwoofyoucantrytobreakeachotherrsquoscodeandfixitGiveyourfriendyourex6pyfilesotheycanbreaksomethingThenyoutrytofindtheirerrorandfixitHavefunwiththisandrememberthatifyouwrotethiscodeonceyoucandoitagainIfyoutakeyourdamagetoofaryoucanalwaystypeitinagainforextrapractice

CommonStudentQuestionsWhydoyouput(single-quotes)aroundsomestringsandnotothersMostlyitrsquosbecauseofstylebutIrsquolluseasingle-quoteinsideastringthathasdouble-quotesLookatlines6and15toseehowIrsquomdoingthat

Ifyouthoughtthejokewasfunnycouldyouwritehilarious=TrueYesandyoursquolllearnmoreaboutthesebooleanvaluesinExercise27

Exercise7MorePrinting

NowwearegoingtodoabunchofexerciseswhereyoujusttypecodeinandmakeitrunIwonrsquotbeexplainingthisexercisebecauseitismoreofthesameThepurposeistobuildupyourchopsSeeyouinafewexercisesanddonotskipDonotpasteClickheretoviewcodeimage

ex7py

1print(Maryhadalittlelamb)

2print(Itsfleecewaswhiteasformat(snow))

3print(AndeverywherethatMarywent)

4print(10)whatdthatdo

5

6end1=C

7end2=h

8end3=e

9end4=e

10end5=s

11end6=e

12end7=B

13end8=u

14end9=r

15end10=g

16end11=e

17end12=r

18

19watchthatcommaattheendtryremovingittoseewhat

happens

20print(end1+end2+end3+end4+end5+end6end=)

21print(end7+end8+end9+end10+end11+end12)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise7Session

$python36ex7py

Maryhadalittlelamb

Itsfleecewaswhiteassnow

AndeverywherethatMarywent

CheeseBurger

StudyDrillsForthesenextfewexercisesyouwillhavetheexactsameStudyDrills

1Gobackthroughandwriteacommentonwhateachlinedoes2Readeachonebackwardoroutloudtofindyourerrors3Fromnowonwhenyoumakemistakeswritedownonapieceofpaperwhatkindofmistakeyoumade

4Whenyougotothenextexerciselookatthemistakesyouhavemadeandtrynottomaketheminthisnewone

5RememberthateveryonemakesmistakesProgrammersarelikemagicianswhofooleveryoneintothinkingtheyareperfectandneverwrongbutitrsquosallanactTheymakemistakesallthetime

BreakItDidyouhavefunbreakingthecodeinExercise6FromnowonyoursquoregoingtobreakallthecodeyouwriteorafriendrsquoscodeIwonrsquothaveaBreakItsectionexplicitlyineveryexercisebutIwilldothisinalmosteveryvideoYourgoalistofindasmanydifferentwaystobreakyourcodeuntilyougettiredorexhaustallpossibilitiesInsomeexercisesImightpointoutaspecificcommonwaypeoplebreakthatexercisersquoscodebutotherwiseconsiderthisastandingordertoalwaysbreakit

CommonStudentQuestionsWhyareyouusingthevariablenamedsnowThatrsquosactuallynotavariableitisjustastringwiththewordsnowinitAvariablewouldnrsquothavethesingle-quotesaroundit

IsitnormaltowriteanEnglishcommentforeverylineofcodelikeyousaytodoinStudyDrill1Noyouwritecommentsonlytoexplaindifficult-to-understandcodeorwhyyoudidsomethingWhyisusuallymuchmoreimportantandthenyoutrytowritethecodesothatitexplainshowsomethingisbeingdoneonitsownHoweversometimesyouhavetowritesuchnastycodetosolveaproblemthatitdoesneedacommentoneverylineInthiscaseitrsquosstrictlyforyoutopracticetranslatingcodetoEnglish

CanIusesingle-quotesordouble-quotestomakeastringordo

theydodifferentthingsInPythoneitherwaytomakeastringisacceptablealthoughtypicallyyoursquollusesingle-quotesforanyshortstringslikeaorsnow

Exercise8PrintingPrinting

WewillnowseehowtodoamorecomplicatedformattingofastringThiscodelookscomplexbutifyoudoyourcommentsaboveeachlineandbreakeachthingdowntoitspartsyoursquollunderstanditClickheretoviewcodeimage

ex8py

1formatter=

2

3print(formatterformat(1234))

4print(formatterformat(onetwothreefour))

5print(formatterformat(TrueFalseFalseTrue))

6print(formatterformat(formatterformatterformatter

formatter))

7print(formatterformat(

8Tryyour

9Owntexthere

10Maybeapoem

11Orasongaboutfear

12))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise8Session

$python36ex8py

1234

onetwothreefour

TrueFalseFalseTrue

TryyourOwntexthereMaybeapoemOrasongaboutfearInthis

exerciseIrsquomusingsomethingcalledafunctiontoturntheformatter

variableintootherstringsWhenyouseemewrite

formatterformat()Irsquomtellingpythontodothefollowing1Take

theformatterstringdefinedonline1

2Callitsformatfunctionwhichissimilartotellingittodoacommandlinecommandnamedformat

3PasstoformatfourargumentswhichmatchupwiththefoursintheformattervariableThisislikepassingargumentstothecommandlinecommandformat

4TheresultofcallingformatonformatterisanewstringthathasthereplacedwiththefourvariablesThisiswhatprintisnowprintingout

ThatrsquosalotfortheeighthexercisesowhatIwantyoutodoisconsiderthisabrainteaserItrsquosalrightifyoudonrsquotreallyunderstandwhatrsquosgoingonbecausetherestofthebookwillslowlymakethisclearAtthispointtrytostudythisandseewhatrsquosgoingonthenmoveontothenextexercise

StudyDrillsDoyourcheckswritedownyourmistakesandtrynottomakethesamemistakesonthenextexerciseInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIhavetoputquotesaroundonebutnotaroundTrueorFalsePythonrecognizesTrueandFalseaskeywordsrepresentingtheconceptoftrueandfalseIfyouputquotesaroundthemthentheyareturnedintostringsandwonrsquotworkYoursquolllearnmoreabouthowtheseworkinExercise27

CanIuseIDLEtorunthisNoyoushouldlearntousethecommandlineItisessentialtolearningprogrammingandisagoodplacetostartifyouwanttolearnaboutprogrammingIDLEwillfailforyouwhenyougetfurtherinthebook

Exercise9PrintingPrintingPrinting

BynowyoushouldrealizethepatternforthisbookistousemorethanoneexercisetoteachyousomethingnewIstartwithcodethatyoumightnotunderstandthenmoreexercisesexplaintheconceptIfyoudonrsquotunderstandsomethingnowyouwilllaterasyoucompletemoreexercisesWritedownwhatyoudonrsquotunderstandandkeepgoingClickheretoviewcodeimage

ex9py

1Heressomenewstrangestuffremembertypeitexactly

2

3days=MonTueWedThuFriSatSun

4months=JannFebnMarnAprnMaynJunnJulnAug

5

6print(Herearethedaysdays)

7print(Herearethemonthsmonths)

8

9print(

10Theressomethinggoingonhere

11Withthethreedouble-quotes

12Wellbeabletotypeasmuchaswelike

13Even4linesifwewantor5or6

14)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise9Session

$python36ex9py

HerearethedaysMonTueWedThuFriSatSun

HerearethemonthsJan

Feb

Mar

Apr

May

Jun

Jul

Aug

Theressomethinggoingonhere

Withthethreedouble-quotes

Wellbeabletotypeasmuchaswelike

Even4linesifwewantor5or6

StudyDrillsCheckyourworkwritedownyourmistakestrynottomakethemonthenextexerciseAreyoubreakingyourcodeandthenfixingitInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIgetanerrorwhenIputspacesbetweenthethreedouble-quotesYouhavetotypethemlikeandnotmeaningwithnospacesbetweeneachone

WhatifIwantedtostartthemonthsonanewlineYousimplystartthestringwithnlikethisClickheretoviewcodeimagenJannFebnMarnAprnMaynJunnJulnAug

IsitbadthatmyerrorsarealwaysspellingmistakesMostprogrammingerrorsinthebeginning(andevenlater)aresimplespellingmistakestyposorgettingsimplethingsoutoforder

Exercise10WhatWasThat

InExercise9IthrewyousomenewstuffjusttokeepyouonyourtoesIshowedyoutwowaystomakeastringthatgoesacrossmultiplelinesInthefirstwayIputthecharactersn(backslashn)betweenthenamesofthemonthsThesetwocharactersputanewlinecharacterintothestringatthatpointThis(backslash)characterencodesdifficult-to-typecharactersintoastringTherearevariousescapesequencesavailablefordifferentcharactersyoumightwanttouseWersquolltryafewofthesesequencessoyoucanseewhatImeanAnimportantescapesequenceistoescapeasingle-quote()ordouble-quote()Imagineyouhaveastringthatusesdouble-quotesandyouwanttoputadouble-quoteinsidethestringIfyouwriteIunderstandjoethenPythonwillgetconfusedbecauseitwillthinkthedouble-quotesaroundunderstandactuallyendsthestringYouneedawaytotellPythonthatthedouble-quoteinsidethestringisnrsquotarealdouble-quoteTosolvethisproblemyouescapedouble-quotesandsingle-quotessoPythonknowstoincludetheminthestringHerersquosanexampleClickheretoviewcodeimage

Iam62tallescapedoublendashquoteinsidestring

Iam62tallescapesinglendashquoteinsidestringThesecond

wayisbyusingtriple-quoteswhichisjustandworkslikea

stringbutyoualsocanputasmanylinesoftextasyouwantuntil

youtypeagainWersquollalsoplaywiththese

Clickheretoviewcodeimage

ex10py

1tabby_cat=tImtabbedin

2persian_cat=Imsplitnonaline

3backslash_cat=Imacat

4

5fat_cat=

6Illdoalist

7tCatfood

8tFishies

9tCatnipntGrass

10

11

12print(tabby_cat)

13print(persian_cat)

14print(backslash_cat)

15print(fat_cat)

WhatYouShouldSeeLookforthetabcharactersthatyoumadeInthisexercisethespacingisimportanttogetright

$pythonex10py

Imtabbedin

Imsplit

onaline

Imacat

Illdoalist

Catfood

Fishies

Catnip

Grass

EscapeSequencesThisisalloftheescapesequencesPythonsupportsYoumaynotusemanyofthesebutmemorizetheirformatandwhattheydoanywayTrythemoutinsomestringstoseeifyoucanmakethemwork

StudyDrills1Memorizealltheescapesequencesbyputtingthemonflashcards2Use(triple-single-quote)insteadCanyouseewhyyoumightusethatinsteadof

3Combineescapesequencesandformatstringstocreateamorecomplexformat

CommonStudentQuestionsIstillhavenrsquotcompletelyfiguredoutthelastexerciseShouldIcontinueYeskeepgoingInsteadofstoppingtakenoteslistingthingsyoudonrsquotunderstandforeachexercisePeriodicallygothroughyournotesandseeifyoucanfigurethesethingsoutafteryoursquovecompletedmoreexercisesSometimesthoughyoumayneedtogobackafewexercisesanddothemagain

WhatmakesspecialcomparedtotheotheronesItrsquossimplythewayyouwouldwriteoutonebackslash()characterThinkaboutwhyyouwouldneedthis

WhenIwriteornitdoesnrsquotworkThatrsquosbecauseyouareusingaforward-slash()andnotabackslash()Theyaredifferentcharactersthatdoverydifferentthings

IdonrsquotgetStudyDrill3WhatdoyoumeanbyldquocombinerdquoescapesequencesandformatsOneconceptIneedyoutounderstandisthateachoftheseexercisescanbecombinedtosolveproblemsTakewhatyouknowaboutformatstringsandwritesomenewcodethatusesformatstringsandtheescapesequencesfromthisexercise

WhatrsquosbetterorItrsquosentirelybasedonstyleGowiththe(triple-single-quote)stylefornowbutbereadytouseeitherdependingonwhatfeelsbestorwhateveryoneelseisdoing

Exercise11AskingQuestions

NowitistimetopickupthepaceYouaredoingalotofprintingtogetyoufamiliarwithtypingsimplethingsbutthosesimplethingsarefairlyboringWhatwewanttodonowisgetdataintoyourprogramsThisisalittletrickybecauseyouhavetolearntodotwothingsthatmaynotmakesenserightawaybuttrustmeanddoitanywayItwillmakesenseinafewexercisesMostofwhatsoftwaredoesisthefollowing1Takessomekindofinputfromaperson

2Changesit3Printsoutsomethingtoshowhowitchanged

SofaryouhavebeenprintingstringsbutyouhavenrsquotbeenabletogetanyinputfromapersonYoumaynotevenknowwhatldquoinputrdquomeansbuttypethiscodeinanywayandmakeitexactlythesameInthenextexercisewersquolldomoretoexplaininputClickheretoviewcodeimage

ex11py

1print(Howoldareyouend=)

2age=input()

3print(Howtallareyouend=)

4height=input()

5print(Howmuchdoyouweighend=)

6weight=input()

7

8print(fSoyoureageoldheighttallandweight

heavy)

WarningWeputanend=attheendofeachprintlineThistellsprinttonotendthelinewithanewlinecharacterandgotothenextline

WhatYouShouldSeeClickheretoviewcodeimage

Exercise11Session

$python36ex11py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1GoonlineandfindoutwhatPythonrsquosinputdoes2CanyoufindotherwaystouseitTrysomeofthesamplesyoufind3Writeanotherldquoformrdquolikethistoasksomeotherquestions

CommonStudentQuestionsHowdoIgetanumberfromsomeonesoIcandomathThatrsquosalittleadvancedbuttryx=int(input())whichgetsthenumberasastringfrominput()thenconvertsittoanintegerusingint()

Iputmyheightintorawinputlikethisinput(62)butitdoesnrsquotworkDonrsquotputyourheightintheretypeitdirectlyintoyourTerminalFirstgobackandmakethecodeexactlylikemineNextrunthescriptandwhenitpausestypeyourheightinatyourkeyboardThatrsquosallthereistoit

Exercise12PromptingPeople

Whenyoutypedinput()youweretypingthe(and)characterswhichareparenthesischaractersThisissimilartowhenyouusedthemtodoaformatwithextravariablesasinfxyForinputyoucanalsoputinaprompttoshowtoapersonsoheknowswhattotypePutastringthatyouwantforthepromptinsidethe()sothatitlookslikethis

y=input(Name)

ThispromptstheuserwithldquoNamerdquoandputstheresultintothevariableyThisishowyouasksomeoneaquestionandgettheanswerThismeanswecancompletelyrewriteourpreviousexerciseusingjustinputtodoallthepromptingClickheretoviewcodeimage

ex12py

1age=input(Howoldareyou)

2height=input(Howtallareyou)

3weight=input(Howmuchdoyouweigh)

4

5print(fSoyoureageoldheighttallandweight

heavy)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise12Session

$python36ex12py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1InTerminalwhereyounormallyrunpython36torunyourscriptstypepydocinputReadwhatitsaysIfyoursquoreonWindowstry

python36-mpydocinputinstead2Getoutofpydocbytypingqtoquit3Lookonlineforwhatthepydoccommanddoes4UsepydoctoalsoreadaboutopenfileosandsysItrsquosalrightifyoudonotunderstandthosejustreadthroughandtakenotesaboutinterestingthings

CommonStudentQuestionsHowcomeIgetSyntaxErrorinvalidsyntaxwheneverIrunpydocYouarenrsquotrunningpydocfromthecommandlineyoursquoreprobablyrunningitfrominsidepython36Exitoutofpython36first

WhydoesmypydocnotpauselikeyoursdoesSometimesifthehelpdocumentisshortenoughtofitononescreenthenpydocwilljustprintit

WhenIrunpydocIgetmoreisnotrecognizedasaninternalSomeversionsofWindowsdonothavethatcommandwhichmeanspydocisbrokenforyouYoucanskipthisStudyDrillandjustsearchonlineforPythondocumentationwhenyouneedit

WhycanrsquotIdoprint(Howoldareyouinput())Youcanbutthentheresultofcallinginput()isneversavedtoavariableanditrsquollworkinastrangewayTrythisandthentrytoprintoutwhatyoutypeSeeifyoucandebugwhythisisnrsquotworking

Exercise13ParametersUnpackingVariables

Inthisexercisewewillcoveronemoreinputmethodyoucanusetopassvariablestoascript(scriptbeinganothernameforyourpyfiles)Youknowhowyoutypepython36ex13pytoruntheex13pyfileWelltheex13pypartofthecommandiscalledanargumentWhatwersquolldonowiswriteascriptthatalsoacceptsargumentsTypethisprogramandIrsquollexplainitindetailClickheretoviewcodeimage

ex13py

1fromsysimportargv

2readtheWYSSsectionforhowtorunthis

3scriptfirstsecondthird=argv

4

5print(Thescriptiscalledscript)

6print(Yourfirstvariableisfirst)

7print(Yoursecondvariableissecond)

8print(Yourthirdvariableisthird)

Online1wehavewhatrsquoscalledanimportThisishowyouaddfeaturestoyourscriptfromthePythonfeaturesetRatherthangiveyouallthefeaturesatoncePythonasksyoutosaywhatyouplantouseThiskeepsyourprogramssmallbutitalsoactsasdocumentationforotherprogrammerswhoreadyourcodelaterTheargvistheargumentvariableaverystandardnameinprogrammingthatyouwillfindusedinmanyotherlanguagesThisvariableholdstheargumentsyoupasstoyourPythonscriptwhenyourunitIntheexercisesyouwillgettoplaywiththismoreandseewhathappensLine3unpacksargvsothatratherthanholdingalltheargumentsitgetsassignedtofourvariablesyoucanworkwithscriptfirstsecondandthirdThismaylookstrangebutldquounpackrdquoisprobablythebestwordtodescribewhatitdoesItjustsaysldquoTakewhateverisinargvunpackitandassignittoallofthesevariablesontheleftinorderrdquoAfterthatwejustprintthemoutlikenormal

HoldUpFeaturesHaveAnotherName

Icallthemldquofeaturesrdquohere(theselittlethingsyouimporttomakeyourPythonprogramdomore)butnobodyelsecallsthemfeaturesIjustusedthatnamebecauseIneededtotrickyouintolearningwhattheyarewithoutjargonBeforeyoucancontinueyouneedtolearntheirrealnamemodulesFromnowonwewillbecallingtheseldquofeaturesrdquothatweimportmodulesIrsquollsaythingslikeldquoYouwanttoimportthesysmodulerdquoTheyarealsocalledldquolibrariesrdquobyotherprogrammersbutletrsquosjuststickwithmodules

WhatYouShouldSee

WarningPayattentionYouhavebeenrunningpythonscriptswithoutcommandlineargumentsIfyoutypeonlypython36ex13pyyouaredoingitwrongPaycloseattentiontohowIrunitThisappliesanytimeyouseeargvbeingused

Runtheprogramlikethis(andyoumustpassthreecommandlinearguments)Clickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd3rd

Thescriptiscalledex13py

Yourfirstvariableisfirst

Yoursecondvariableis2nd

Yourthirdvariableis3rd

ThisiswhatyoushouldseewhenyoudoafewdifferentrunswithdifferentargumentsClickheretoviewcodeimage

Exercise13Session

$python36ex13pystuffthingsthat

Thescriptiscalledex13py

Yourfirstvariableisstuff

Yoursecondvariableisthings

Yourthirdvariableisthat

$

$python36ex13pyappleorangegrapefruit

Thescriptiscalledex13py

Yourfirstvariableisapple

Yoursecondvariableisorange

Yourthirdvariableisgrapefruit

Youcanactuallyreplacefirst2ndand3rdwithanythreethingsyouwantIfyoudonotrunitcorrectlythenyouwillgetanerrorlikethisClickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd

Traceback(mostrecentcalllast)

Fileex13pyline3inltmodulegt

scriptfirstsecondthird=argv

ValueErrornotenoughvaluestounpack(expected4got3)

Thishappenswhenyoudonotputenoughargumentsonthecommandwhenyourunit(inthiscasejustfirst2nd)NoticethatwhenIrunitIgiveitfirst2ndwhichcausedittogiveanerroraboutldquoneedmorethan3valuestounpackrdquotellingyouthatyoudidnrsquotgiveitenoughparameters

StudyDrills1TrygivingfewerthanthreeargumentstoyourscriptSeethaterroryougetSeeifyoucanexplainit

2WriteascriptthathasfewerargumentsandonethathasmoreMakesureyougivetheunpackedvariablesgoodnames

3CombineinputwithargvtomakeascriptthatgetsmoreinputfromauserDonrsquotoverthinkitJustuseargvtogetsomethingandinputtogetsomethingelsefromtheuser

4RememberthatmodulesgiveyoufeaturesModulesModulesRememberthisbecausewersquollneeditlater

CommonStudentQuestionsWhenIrunitIgetValueErrorneedmorethan1valuetounpackRememberthatanimportantskillispayingattentiontodetailsIfyoulookattheWhatYouShouldSeesectionyouseethatIrunthescriptwithparametersonthecommandlineYoushouldreplicatehowIranitexactly

Whatrsquosthedifferencebetweenargvandinput()ThedifferencehastodowithwheretheuserisrequiredtogiveinputIftheygiveyourscriptinputsonthecommandlinethenyouuseargvIfyouwantthemtoinputusingthekeyboardwhilethescriptisrunningthenuseinput()

ArethecommandlineargumentsstringsYestheycomeinasstringsevenifyoutypednumbersonthecommandlineUseint()toconvertthemlikewithint(input())

HowdoyouusethecommandlineYoushouldhavelearnedtouseitveryquicklyandfluentlybynowbutifyouneedtolearnitatthisstagethenreadtheappendix

Icanrsquotcombineargvwithinput()DonrsquotoverthinkitJustslaptwolinesattheendofthisscriptthatuseinput()togetsomethingandthenprintitFromthatstartplayingwithmorewaystousebothinthesamescript

WhycanrsquotIdothisinput()=xBecausethatrsquosbackwardtohowitshouldworkDoitthewayIdoitanditrsquollwork

Exercise14PromptingandPassing

LetrsquosdooneexercisethatusesargvandinputtogethertoasktheusersomethingspecificYouwillneedthisforthenextexercisewhereyoulearntoreadandwritefilesInthisexercisewersquolluseinputslightlydifferentlybyhavingitprintasimplegtpromptThisissimilartogameslikeZorkorAdventureClickheretoviewcodeimage

ex14py

1fromsysimportargv

2

3scriptuser_name=argv

4prompt=gt

5

6print(fHiuser_nameImthescriptscript)

7print(Idliketoaskyouafewquestions)

8print(fDoyoulikemeuser_name)

9likes=input(prompt)

10

11print(fWheredoyouliveuser_name)

12lives=input(prompt)

13

14print(Whatkindofcomputerdoyouhave)

15computer=input(prompt)

16

17print(f

18Alrightsoyousaidlikesaboutlikingme

19YouliveinlivesNotsurewherethatis

20AndyouhaveacomputercomputerNice

21)Wemakeavariablepromptthatissettothepromptwe

wantandwegivethattoinputinsteadoftypingitoverandover

Nowifwewanttomakethepromptsomethingelsewejustchangeit

inthisonespotandrerunthescriptVeryhandy

WhatYouShouldSeeWhenyourunthisrememberthatyouhavetogivethescriptyournamefortheargvargumentsClickheretoviewcodeimage

Exercise14Session

$python36ex14pyzed

HizedImtheex14pyscript

Idliketoaskyouafewquestions

Doyoulikemezed

gtYes

Wheredoyoulivezed

gtSanFrancisco

Whatkindofcomputerdoyouhave

gtTandy1000

AlrightsoyousaidYesaboutlikingme

YouliveinSanFranciscoNotsurewherethatis

AndyouhaveaTandy1000computerNice

StudyDrills1FindoutwhatthegamesZorkandAdventurewereTrytofindcopiesandplaythem

2Changethepromptvariabletosomethingelseentirely3Addanotherargumentanduseitinyourscriptthesamewayyoudidinthepreviousexercisewithfirstsecond=ARGV

4MakesureyouunderstandhowIcombinedastylemultilinestringwiththeformatactivatorasthelastprint

CommonStudentQuestionsIgetSyntaxErrorinvalidsyntaxwhenIrunthisscriptAgainyouhavetorunitrightonthecommandlinenotinsidePythonIfyoutypepython36andthentrytotypepython36ex14pyZeditwillfailbecauseyouarerunningPythoninsidePythonCloseyourwindowandthenjusttypepython36ex14pyZed

IdonrsquotunderstandwhatyoumeanbychangingthepromptSeethevariableprompt=gtChangethattohaveadifferentvalueYouknowthisitrsquosjustastringandyoursquovedone13exercisesmakingthemsotakethetimetofigureitout

IgettheerrorValueErrorneedmorethan1valuetounpackRememberwhenIsaidyouneedtolookattheWhatYouShouldSeesectionandreplicatewhatIdidYouneedtodothesamethinghereandfocusonhowItypethecommandinandwhyIhaveacommandlineargument

HowcanIrunthisfromIDLEDonrsquotuseIDLECanIusedouble-quotesforthepromptvariableYoutotallycanGoaheadandtrythat

YouhaveaTandycomputerIdidwhenIwaslittleIgetNameErrornamepromptisnotdefinedwhenIrunitYoueitherspelledthenameofthepromptvariablewrongorforgotthatlineGobackandcompareeachlineofcodetominestartingatthebottomofthescriptandworkinguptothetopAnytimeyouseethiserroritmeansyouspelledsomethingwrongorforgottocreatethevariable

Exercise15ReadingFiles

YouknowhowtogetinputfromauserwithinputorargvNowyouwilllearnaboutreadingfromafileYoumayhavetoplaywiththisexercisethemosttounderstandwhatrsquosgoingonsodotheexercisecarefullyandrememberyourchecksWorkingwithfilesisaneasywaytoeraseyourworkifyouarenotcarefulThisexerciseinvolveswritingtwofilesOneistheusualex15pyfilethatyouwillrunbuttheotherisnamedex15_sampletxtThissecondfileisnrsquotascriptbutaplaintextfilewersquollbereadinginourscriptHerearethecontentsofthatfileClickheretoviewcodeimage

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

WhatwewanttodoisopenthatfileinourscriptandprintitoutHoweverwedonotwanttojusthardcodethenameex15_sampletxtintoourscriptldquoHardcodingrdquomeansputtingsomebitofinformationthatshouldcomefromtheuserasastringdirectlyinoursourcecodeThatrsquosbadbecausewewantittoloadotherfileslaterThesolutionistouseargvorinputtoasktheuserwhatfiletoopeninsteadofhardcodingthefilersquosnameClickheretoviewcodeimage

ex15py

1fromsysimportargv

2

3scriptfilename=argv

4

5txt=open(filename)

6

7print(fHeresyourfilefilename)

8print(txtread())

9

10print(Typethefilenameagain)

11file_again=input(gt)

12

13txt_again=open(file_again)

14

15print(txt_againread())Afewfancythingsaregoingoninthis

filesoletrsquosbreakitdownrealquicklybullLines1ndash3useargvto

getafilenameNextwehaveline5whereweuseanewcommand

openRightnowrunpydocopenandreadtheinstructionsNotice

howlikeyourownscriptsandinputittakesaparameterand

returnsavalueyoucansettoyourownvariableYoujustopeneda

file

bullLine7printsalittlemessagebutonline8wehavesomethingverynewandexcitingWecallafunctionontxtnamedreadWhatyougetbackfromopenisafileanditalsohascommandsyoucangiveitYougiveafileacommandbyusingthe(dotorperiod)thenameofthecommandandparametersjustlikewithopenandinputThedifferenceisthattxtread()saysldquoHeytxtDoyourreadcommandwithnoparametersrdquo

TheremainderofthefileismoreofthesamebutwersquollleavetheanalysistoyouintheStudyDrills

WhatYouShouldSee

WarningPayattentionIsaidpayattentionYouhavebeenrunningscriptswithjustthenameofthescriptbutnowthatyouareusingargvyouhavetoaddargumentsLookattheveryfirstlineoftheexamplebelowandyouwillseeIdopythonex15pyex15_sampletxttorunitSeetheextraargumentex15_sampletxtaftertheex15pyscriptnameIfyoudonottypethatyouwillgetanerrorsopayattention

Imadeafilecalledex15_sampletxtandranmyscriptClickheretoviewcodeimage

Exercise15Session

$python36ex15pyex15_sampletxt

Heresyourfileex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

Typethefilenameagain

gtex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

StudyDrillsThisisabigjumpsobesureyoudothisStudyDrillasbestyoucanbeforemovingon

1AboveeachlinecommentoutinEnglishwhatthatlinedoes2IfyouarenotsureasksomeoneforhelporsearchonlineManytimessearchingforldquopython36THINGrdquowillfindanswerstowhatthatTHINGdoesinPythonTrysearchingforldquopython36openrdquo

3IusedthewordldquocommandsrdquoherebutcommandsarealsocalledldquofunctionsrdquoandldquomethodsrdquoYouwilllearnaboutfunctionsandmethodslaterinthebook

4Getridoflines10ndash15whereyouuseinputandrunthescriptagain5UseonlyinputandtrythescriptthatwayWhyisonewayofgettingthefilenamebetterthananother

6Startpython36tostartthepython36shellanduseopenfromthepromptjustlikeinthisprogramNoticehowyoucanopenfilesandrunreadonthemfromwithinpython36

7Haveyourscriptalsocallclose()onthetxtandtxt_againvariablesItrsquosimportanttoclosefileswhenyouaredonewiththem

CommonStudentQuestionsDoestxt=open(filename)returnthecontentsofthefileNoitdoesnrsquotItactuallymakessomethingcalledafileobjectYoucanthinkofafilelikeanoldtapedrivethatyousawonmainframecomputersinthe1950sorevenlikeaDVDplayerfromtodayYoucanmovearoundinsidethemandthenldquoreadrdquothembuttheDVDplayerisnottheDVDthesamewaythefileobjectisnotthefilersquoscontents

IcanrsquottypecodeintoTerminalPowerShelllikeyousayinStudyDrill7Firstfromthecommandlinejusttypepython36andpressEnterNowyouareinpython36aswersquovedoneafewothertimesThenyoucantypeincodeandPythonwillrunitinlittlepiecesPlaywiththatTogetoutofittypequit()andhitEnter

WhyistherenoerrorwhenweopenthefiletwicePythonwillnotrestrictyoufromopeningafilemorethanonceandsometimesthisisnecessary

WhatdoesfromsysimportargvmeanFornowjustunderstandthatsysisapackageandthisphrasejustsaystogettheargvfeaturefromthatpackageYoursquolllearnmoreabouttheselater

Iputthenameofthefileinasscriptex15_sampletxt=argvbutitdoesnrsquotworkNothatrsquosnothowyoudoitMakethecodeexactlylikeminethenrunitfromthecommandlinetheexactsamewayIdoYoudonrsquotputthenamesoffilesinyouletPythonputthenamein

Exercise16ReadingandWritingFiles

IfyoudidtheStudyDrillsfromthelastexerciseyoushouldhaveseenallsortsofcommands(methodsfunctions)youcangivetofilesHerersquosthelistofcommandsIwantyoutorememberbullcloseClosesthefileLikeFile-gtSaveinyoureditor

bullreadReadsthecontentsofthefileYoucanassigntheresulttoavariable

bullreadlineReadsjustonelineofatextfilebulltruncateEmptiesthefileWatchoutifyoucareaboutthefilebullwrite(stuff)Writesldquostuffrdquotothefilebullseek(0)Movesthereadwritelocationtothebeginningofthefile

OnewaytorememberwhateachofthesedoesistothinkofavinylrecordcassettetapeVHStapeDVDorCDplayerIntheearlydaysofcomputersdatawasstoredoneachofthesekindsofmediasomanyofthefileoperationsstillresembleastoragesystemthatislinearTapeandDVDdrivesneedtoldquoseekrdquoaspecificspotandthenyoucanreadorwriteatthatspotTodaywehaveoperatingsystemsandstoragemediathatblurthelinesbetweenrandomaccessmemoryanddiskdrivesbutwestillusetheolderideaofalineartapewithareadwriteheadthatmustbemovedFornowthesearetheimportantcommandsyouneedtoknowSomeofthemtakeparametersbutwedonotreallycareaboutthatYouonlyneedtorememberthatwritetakesaparameterofastringyouwanttowritetothefileLetrsquosusesomeofthistomakeasimplelittletexteditorClickheretoviewcodeimage

ex16py

1fromsysimportargv

2

3scriptfilename=argv

4

5print(fWeregoingtoerasefilename)

6print(IfyoudontwantthathitCTRL-C(^C))

7print(IfyoudowantthathitRETURN)

8

9input()

10

11print(Openingthefile)

12target=open(filenamew)

13

14print(TruncatingthefileGoodbye)

15targettruncate()

16

17print(NowImgoingtoaskyouforthreelines)

18

19line1=input(line1)

20line2=input(line2)

21line3=input(line3)

22

23print(Imgoingtowritethesetothefile)

24

25targetwrite(line1)

26targetwrite(n)

27targetwrite(line2)

28targetwrite(n)

29targetwrite(line3)

30targetwrite(n)

31

32print(Andfinallywecloseit)

33targetclose()

ThatrsquosalargefileprobablythelargestyouhavetypedinSogoslowdoyourchecksandmakeitrunOnetrickistogetbitsofitrunningatatimeGetlines1ndash8runningthenfivemorethenafewmoreuntilitrsquosalldoneandrunning

WhatYouShouldSeeThereareactuallytwothingsyouwillseeFirsttheoutputofyournewscriptClickheretoviewcodeimage

Exercise16Session

$python36ex16pytesttxt

Weregoingtoerasetesttxt

IfyoudontwantthathitCTRL-C(^C)

IfyoudowantthathitRETURN

Openingthefile

TruncatingthefileGoodbye

NowImgoingtoaskyouforthreelines

line1Maryhadalittlelamb

line2Itsfleecewaswhiteassnow

line3Itwasalsotasty

Imgoingtowritethesetothefile

Andfinallywecloseit

Nowopenupthefileyoumade(inmycasetesttxt)inyoureditorandcheckitoutNeatright

StudyDrills1IfyoudonotunderstandthisgobackthroughandusethecommenttricktogetitsquaredawayinyourmindOnesimpleEnglishcommentaboveeachlinewillhelpyouunderstandoratleastletyouknowwhatyouneedtoresearchmore

2Writeascriptsimilartothelastexercisethatusesreadandargvtoreadthefileyoujustcreated

3TherersquostoomuchrepetitioninthisfileUsestringsformatsandescapestoprintoutline1line2andline3withjustonetargetwrite()commandinsteadofsix

4FindoutwhywehadtopassawasanextraparametertoopenHintopentriestobesafebymakingyouexplicitlysayyouwanttowriteafile

5Ifyouopenthefilewithwmodethendoyoureallyneedthetargettruncate()ReadthedocumentationforPythonrsquosopenfunctionandseeifthatrsquostrue

CommonStudentQuestionsIsthetruncate()necessarywiththewparameterSeeStudyDrillsnumber5

WhatdoeswmeanItrsquosreallyjustastringwithacharacterinitforthekindofmodeforthefileIfyouusewthenyoursquoresayingldquoopenthisfileinlsquowritersquomoderdquothusthewcharacterTherersquosalsorforldquoreadrdquoaforldquoappendrdquoandmodifiersonthese

WhatmodifierstothefilemodescanIuseThemostimportantonetoknowfornowisthe+modifiersoyoucandow+r+anda+Thiswillopenthefileinbothreadandwritemodeanddependingonthecharacterusepositionthefileindifferentways

Doesjustdoingopen(filename)openitinr(read)modeYesthatrsquosthedefaultfortheopen()function

Exercise17MoreFiles

NowletrsquosdoafewmorethingswithfilesWersquollwriteaPythonscripttocopyonefiletoanotherItrsquollbeveryshortbutwillgiveyouideasaboutotherthingsyoucandowithfilesClickheretoviewcodeimage

ex17py

1fromsysimportargv

2fromospathimportexists

3

4scriptfrom_fileto_file=argv

5

6print(fCopyingfromfrom_filetoto_file)

7

8wecoulddothesetwoononelinehow

9in_file=open(from_file)

10indata=in_fileread()

11

12print(fTheinputfileislen(indata)byteslong)

13

14print(fDoestheoutputfileexistexists(to_file))

15print(ReadyhitRETURNtocontinueCTRL-Ctoabort)

16input()

17

18out_file=open(to_filew)

19out_filewrite(indata)

20

21print(Alrightalldone)

22

23out_fileclose()

24in_fileclose()Youshouldimmediatelynoticethatweimport

anotherhandycommandnamedexistsThisreturnsTrueifafile

existsbasedonitsnameinastringasanargumentItreturns

FalseifnotWersquollbeusingthisfunctioninthesecondhalfofthis

booktodolotsofthingsbutrightnowyoushouldseehowyoucan

importit

Usingimportisawaytogettonsoffreecodeotherbetter(wellusually)programmershavewrittensoyoudonothavetowriteit

WhatYouShouldSee

JustlikeyourotherscriptsrunthisonewithtwoargumentsthefiletocopyfromandthefiletocopyittoIrsquomgoingtouseasimpletestfilenamedtesttxtClickheretoviewcodeimage

Exercise17Session

$firstmakeasamplefile

$echoThisisatestfilegttesttxt

$thenlookatit

$cattesttxt

Thisisatestfile

$nowrunourscriptonit

$python36ex17pytesttxtnew_filetxt

Copyingfromtesttxttonew_filetxt

Theinputfileis21byteslong

DoestheoutputfileexistFalse

ReadyhitRETURNtocontinueCTRL-Ctoabort

Alrightalldone

ItshouldworkwithanyfileTryabunchmoreandseewhathappensJustbecarefulyoudonotblastanimportantfile

WarningDidyouseethetrickIdidwithechotomakeafileandcattoshowthefileYoucanlearnhowtodothatintheAppendixldquoCommandLineCrashCourserdquo

StudyDrills1ThisscriptisreallyannoyingTherersquosnoneedtoaskyoubeforedoingthecopyanditprintstoomuchouttothescreenTrytomakethescriptmorefriendlytousebyremovingfeatures

2SeehowshortyoucanmakethescriptIcouldmakethisonelinelong3NoticeattheendoftheWhatYouShouldSeesectionIusedsomethingcalledcatItrsquosanoldcommandthatconcatenatesfilestogetherbutmostlyitrsquosjustaneasywaytoprintafiletothescreenTypemancattoreadaboutit

4Findoutwhyyouhadtowriteout_fileclose()inthecode

5GoreaduponPythonrsquosimportstatementandstartpython36totryitoutTryimportingsomethingsandseeifyoucangetitrightItrsquosalrightifyoudonot

CommonStudentQuestionsWhyisthewinquotesThatrsquosastringYoursquovebeenusingstringsforawhilenowMakesureyouknowwhatastringis

NowayyoucanmakethisonelineThatdependsonhowyoudefineonelineofcode

IsitnormaltofeellikethisexercisewasreallyhardYesitistotallynormalProgrammingmaynotldquoclickrdquoforyouuntilmaybeevenExercise36oritmightnotuntilyoufinishthebookandthenmakesomethingwithPythonEveryoneisdifferentsojustkeepgoingandkeepreviewingexercisesthatyouhadtroublewithuntilitclicksBepatient

Whatdoesthelen()functiondoItgetsthelengthofthestringthatyoupasstoitthenreturnsthatasanumberPlaywithit

WhenItrytomakethisscriptshorterIgetanerrorwhenIclosethefilesattheendYouprobablydidsomethinglikeindata=open(from_file)read()whichmeansyoudonrsquotneedtothendoin_fileclose()whenyoureachtheendofthescriptItshouldalreadybeclosedbyPythononcethatonelineruns

IgetaSyntaxEOLwhilescanningstringliteralerrorYouforgottoendastringproperlywithaquoteGolookatthatlineagain

Exercise18NamesVariablesCodeFunctions

BigtitlerightIamabouttointroduceyoutothefunctionDumdumdahEveryprogrammerwillgoonandonaboutfunctionsandallthedifferentideasabouthowtheyworkandwhattheydobutIwillgiveyouthesimplestexplanationyoucanuserightnowFunctionsdothreethings1Theynamepiecesofcodethewayvariablesnamestringsandnumbers

2Theytakeargumentsthewayyourscriptstakeargv3Using1and2theyletyoumakeyourownldquomini-scriptsrdquoorldquotinycommandsrdquo

YoucancreateafunctionbyusingtheworddefinPythonIrsquomgoingtohaveyoumakefourdifferentfunctionsthatworklikeyourscriptsandthenIrsquollshowyouhoweachoneisrelatedClickheretoviewcodeimage

ex18py

1thisoneislikeyourscriptswithargv

2defprint_two(args)

3arg1arg2=args

4print(farg1arg1arg2arg2)

5

6okthatargsisactuallypointlesswecanjustdothis

7defprint_two_again(arg1arg2)

8print(farg1arg1arg2arg2)

9

10thisjusttakesoneargument

11defprint_one(arg1)

12print(farg1arg1)

13

14thisonetakesnoarguments

15defprint_none()

16print(Igotnothin)

17

18

19print_two(ZedShaw)

20print_two_again(ZedShaw)

21print_one(First)

22print_none()Letrsquosbreakdownthefirstfunctionprint_two

whichisthemostsimilartowhatyoualreadyknowfrommaking

scripts1WetellPythonwewanttomakeafunctionusingdeffor

ldquodefinerdquo

2OnthesamelineasdefwegivethefunctionanameInthiscasewejustcalleditldquoprint_twordquobutitcouldalsobeldquopeanutsrdquoItdoesnrsquotmatterexceptthatyourfunctionshouldhaveashortnamethatsayswhatitdoes

3Wetellitwewantargs(asteriskargs)whichisalotlikeyourargvparameterbutforfunctionsThishastogoinsideparenthesestowork

4Weendthislinewitha(colon)andstartindenting5Afterthecolonallthelinesthatareindentedfourspaceswillbecomeattachedtoprint_twoOurfirstindentedlineisonethatunpackstheargumentsthesameaswithyourscripts

6Todemonstratehowitworksweprinttheseargumentsoutjustlikewewouldinascript

Theproblemwithprint_twoisthatitrsquosnottheeasiestwaytomakeafunctionInPythonwecanskipthewholeunpackingargumentsandjustusethenameswewantrightinsideparenthesesThatrsquoswhatprint_two_againdoesAfterthatyouhaveanexampleofhowyoumakeafunctionthattakesoneargumentinprint_oneFinallyyouhaveafunctionthathasnoargumentsinprint_none

WarningThisisveryimportantDonotgetdiscouragedrightnowifthisdoesnrsquotquitemakesenseWersquoregoingtodoafewexerciseslinkingfunctionstoyourscriptsandshowyouhowtomakemoreFornowjustkeepthinkingldquomini-scriptrdquowhenIsayldquofunctionrdquoandkeepplayingwiththem

WhatYouShouldSeeIfyourunex18pyyoushouldsee

Exercise18Session

$python36ex18py

arg1Zedarg2Shaw

arg1Zedarg2Shaw

arg1First

Igotnothin

RightawayyoucanseehowafunctionworksNoticethatyouusedyourfunctionsthewayyouusethingslikeexistsopenandothercommandsInfactIrsquovebeentrickingyoubecauseinPythonthosecommandsarejustfunctionsThismeansyoucanmakeyourowncommandsandusetheminyourscriptstoo

StudyDrillsCreateafunctionchecklistforlaterexercisesWritethesechecksonanindexcardandkeepitbyyouwhileyoucompletetherestoftheseexercisesoruntilyoufeelyoudonotneedtheindexcardanymore

1Didyoustartyourfunctiondefinitionwithdef2Doesyourfunctionnamehaveonlycharactersand_(underscore)characters

3Didyouputanopenparenthesisrightafterthefunctionname4Didyouputyourargumentsaftertheparenthesisseparatedbycommas5Didyoumakeeachargumentunique(meaningnoduplicatednames)6Didyouputacloseparenthesisandacolonafterthearguments7DidyouindentalllinesofcodeyouwantinthefunctionfourspacesNomorenoless

8Didyouldquoendrdquoyourfunctionbygoingbacktowritingwithnoindent(dedentingwecallit)

Whenyourun(ldquouserdquoorldquocallrdquo)afunctioncheckthesethings1Didyoucalluserunthisfunctionbytypingitsname

2Didyouputthe(characterafterthenametorunit3Didyouputthevaluesyouwantintotheparenthesesseparatedbycommas

4Didyouendthefunctioncallwitha)characterUsethesetwochecklistsontheremaininglessonsuntilyoudonotneedthemanymoreFinallyrepeatthisafewtimestoyourselfToldquorunrdquoldquocallrdquoorldquouserdquoafunctioneachmeansthesamething

CommonStudentQuestions

CommonStudentQuestionsWhatrsquosallowedforafunctionnameThesameasvariablenamesAnythingthatdoesnrsquotstartwithanumberandislettersnumbersandunderscoreswillwork

WhatdoestheinargsdoThattellsPythontotakealltheargumentstothefunctionandthenputtheminargsasalistItrsquoslikeargvthatyoursquovebeenusingbutforfunctionsItrsquosnotnormallyusedtoooftenunlessspecificallyneeded

ThisfeelsreallyboringandmonotonousThatrsquosgoodItmeansyoursquorestartingtogetbetterattypinginthecodeandunderstandingwhatitdoesTomakeitlessboringtakeeverythingItellyoutotypeinandthenbreakitonpurpose

Exercise19FunctionsandVariables

Functionsmayhavebeenamind-blowingamountofinformationbutdonotworryJustkeepdoingtheseexercisesandgoingthroughyourchecklistfromthelastexerciseandyouwilleventuallygetitThereisonetinypointthatyoumightnothaverealizedwhichwersquollreinforcerightnowThevariablesinyourfunctionarenotconnectedtothevariablesinyourscriptHerersquosanexercisetogetyouthinkingaboutthisClickheretoviewcodeimage

ex19py

1defcheese_and_crackers(cheese_countboxes_of_crackers)

2print(fYouhavecheese_countcheeses)

3print(fYouhaveboxes_of_crackersboxesofcrackers)

4print(Manthatsenoughforaparty)

5print(Getablanketn)

6

7

8print(Wecanjustgivethefunctionnumbersdirectly)

9cheese_and_crackers(2030)

10

11

12print(ORwecanusevariablesfromourscript)

13amount_of_cheese=10

14amount_of_crackers=50

15

16cheese_and_crackers(amount_of_cheeseamount_of_crackers)

17

18

19print(Wecanevendomathinsidetoo)

20cheese_and_crackers(10+205+6)

21

22

23print(Andwecancombinethetwovariablesandmath)

24cheese_and_crackers(amount_of_cheese+100amount_of_crackers

+1000)Thisshowsallthedifferentwayswersquoreabletogiveour

functioncheese_and_crackersthevaluesitneedstoprintthemWe

cangiveitstraightnumbersWecangiveitvariablesWecangive

itmathWecanevencombinemathandvariables

Inawaytheargumentstoafunctionarekindoflikeour=characterwhenwemakeavariableInfactifyoucanuse=tonamesomethingyoucanusually

passittoafunctionasanargument

WhatYouShouldSeeYoushouldstudytheoutputofthisscriptandcompareitwithwhatyouthinkyoushouldgetforeachoftheexamplesinthescriptClickheretoviewcodeimage

Exercise19Session

$python36ex19py

Wecanjustgivethefunctionnumbersdirectly

Youhave20cheeses

Youhave30boxesofcrackers

Manthatsenoughforaparty

Getablanket

ORwecanusevariablesfromourscript

Youhave10cheeses

Youhave50boxesofcrackers

Manthatsenoughforaparty

Getablanket

Wecanevendomathinsidetoo

Youhave30cheeses

Youhave11boxesofcrackers

Manthatsenoughforaparty

Getablanket

Andwecancombinethetwovariablesandmath

Youhave110cheeses

Youhave1050boxesofcrackers

Manthatsenoughforaparty

Getablanket

StudyDrills1GobackthroughthescriptandtypeacommentaboveeachlineexplaininginEnglishwhatitdoes

2Startatthebottomandreadeachlinebackwardsayingalltheimportantcharacters

3Writeatleastonemorefunctionofyourowndesignandrunit10differentways

CommonStudentQuestions

Howcantherepossiblybe10differentwaystorunafunctionBelieveitornottherersquosatheoreticallyinfinitenumberofwaystocallanyfunctionSeehowcreativeyoucangetwithfunctionsvariablesandinputfromauser

IsthereawaytoanalyzewhatthisfunctionisdoingsoIcanunderstanditbetterTherearemanydifferentwaysbuttryputtinganEnglishcommentaboveeachlinedescribingwhatthelinedoesAnothertrickistoreadthecodeoutloudYetanotheristoprintthecodeoutanddrawonthepaperwithpicturesandcommentsshowingwhatrsquosgoingon

WhatifIwanttoasktheuserforthenumbersofcheeseandcrackersYouneedtouseint()toconvertwhatyougetfrominput()

Doesmakingthevariableamount_of_cheesechangethevariablecheese_countinthefunctionNothosevariablesareseparateandliveoutsidethefunctionTheyarethenpassedtothefunctionandtemporaryversionsaremadejustforthefunctionrsquosrunWhenthefunctionexitsthesetemporaryvariablesgoawayandeverythingkeepsworkingKeepgoinginthebookandthisshouldbecomeclearer

Isitbadtohaveglobalvariables(likeamount_of_cheese)withthesamenameasfunctionvariablesYessincethenyoursquorenotquitesurewhichoneyoursquoretalkingaboutButsometimesnecessitymeansyouhavetousethesamenameoryoumightdoitonaccidentJustavoiditwheneveryoucan

IstherealimittothenumberofargumentsafunctioncanhaveItdependsontheversionofPythonandthecomputeryoursquoreonbutitisfairlylargeThepracticallimitthoughisaboutfiveargumentsbeforethefunctionbecomesannoyingtouse

CanyoucallafunctionwithinafunctionYesyoursquollmakeagamethatdoesthislaterinthebook

Exercise20FunctionsandFiles

RememberyourchecklistforfunctionsthendothisexercisepayingcloseattentiontohowfunctionsandfilescanworktogethertomakeusefulstuffClickheretoviewcodeimage

ex20py

1fromsysimportargv

2

3scriptinput_file=argv

4

5defprint_all(f)

6print(fread())

7

8defrewind(f)

9fseek(0)

10

11defprint_a_line(line_countf)

12print(line_countfreadline())

13

14current_file=open(input_file)

15

16print(Firstletsprintthewholefilen)

17

18print_all(current_file)

19

20print(Nowletsrewindkindoflikeatape)

21

22rewind(current_file)

23

24print(Letsprintthreelines)

25

26current_line=1

27print_a_line(current_linecurrent_file)

28

29current_line=current_line+1

30print_a_line(current_linecurrent_file)

31

32current_line=current_line+1

33print_a_line(current_linecurrent_file)Paycloseattentionto

howwepassinthecurrentlinenumbereachtimewerunprint_a_line

WhatYouShouldSee

Clickheretoviewcodeimage

Exercise20Session

$python36ex20pytesttxt

Firstletsprintthewholefile

Thisisline1

Thisisline2

Thisisline3

Nowletsrewindkindoflikeatape

Letsprintthreelines

1Thisisline1

2Thisisline2

3Thisisline3

StudyDrills1WriteanEnglishcommentforeachlinetounderstandwhatthatlinedoes2Eachtimeprint_a_lineisrunyouarepassinginavariablecurrent_lineWriteoutwhatcurrent_lineisequaltooneachfunctioncallandtracehowitbecomesline_countinprint_a_line

3Findeachplaceafunctionisusedandcheckitsdeftomakesurethatyouaregivingittherightarguments

4ResearchonlinewhattheseekfunctionforfiledoesTrypydocfileandseeifyoucanfigureitoutfromthereThentrypydocfileseektoseewhatseekdoes

5Researchtheshorthandnotation+=andrewritethescripttouse+=instead

CommonStudentQuestionsWhatisfintheprint_allandotherfunctionsThefisavariablejustlikeyouhadinotherfunctionsinExercise18exceptthistimeitrsquosafileAfileinPythoniskindoflikeanoldtapedriveonamainframeormaybeaDVDplayerIthasaldquoreadheadrdquoandyoucanldquoseekrdquothisreadheadaroundthefiletopositionsthenworkwithitthereEachtimeyoudofseek(0)yoursquoremovingtothe

startofthefileEachtimeyoudofreadline()yoursquorereadingalinefromthefileandmovingthereadheadtorightafterthenthatendsthatlineThiswillbeexplainedmoreasyougoon

Whydoesseek(0)notsetthecurrent_lineto0Firsttheseek()functionisdealinginbytesnotlinesThecodeseek(0)movesthefiletothe0byte(firstbyte)inthefileSecondcurrent_lineisjustavariableandhasnorealconnectiontothefileatallWearemanuallyincrementingit

Whatis+=YouknowhowinEnglishIcanrewriteldquoitisrdquoasldquoitrsquosrdquoOrIcanrewriteldquoyouarerdquoasldquoyoursquorerdquoInEnglishthisiscalledacontractionandthisiskindoflikeacontractionforthetwooperations=and+Thatmeansx=x+yisthesameasx+=y

Howdoesreadline()knowwhereeachlineisInsidereadline()iscodethatscanseachbyteofthefileuntilitfindsancharacterthenstopsreadingthefiletoreturnwhatitfoundsofarThefilefisresponsibleformaintainingthecurrentpositioninthefileaftereachreadline()callsothatitwillkeepreadingeachline

WhyarethereemptylinesbetweenthelinesinthefileThereadline()functionreturnsthenthatrsquosinthefileattheendofthatlineAddaend=attheendofyourprintfunctioncallstoavoidaddingdoublentoeveryline

Exercise21FunctionsCanReturnSomething

Youhavebeenusingthe=charactertonamevariablesandsetthemtonumbersorstringsWersquorenowgoingtoblowyourmindagainbyshowingyouhowtouse=andanewPythonwordreturntosetvariablestobeavaluefromafunctionTherewillbeonethingtopaycloseattentiontobutfirsttypethisinClickheretoviewcodeimage

ex21py

1defadd(ab)

2print(fADDINGa+b)

3returna+b

4

5defsubtract(ab)

6print(fSUBTRACTINGa-b)

7returna-b

8

9defmultiply(ab)

10print(fMULTIPLYINGab)

11returnab

12

13defdivide(ab)

14print(fDIVIDINGab)

15returnab

16

17

18print(Letsdosomemathwithjustfunctions)

19

20age=add(305)

21height=subtract(784)

22weight=multiply(902)

23iq=divide(1002)

24

25print(fAgeageHeightheightWeightweightIQ

iq)

26

27

28Apuzzlefortheextracredittypeitinanyway

29print(Hereisapuzzle)

30

31what=add(agesubtract(heightmultiply(weightdivide(iq

2))))

32

33print(ThatbecomeswhatCanyoudoitbyhand)Weare

nowdoingourownmathfunctionsforaddsubtractmultiplyand

divideTheimportantthingtonoticeisthelastlinewherewesay

returna+b(inadd)Whatthisdoesisthefollowing1Our

functioniscalledwithtwoargumentsaandb

2WeprintoutwhatourfunctionisdoinginthiscaseldquoADDINGrdquo3WetellPythontodosomethingkindofbackwardwereturntheadditionofa+bYoumightsaythisasldquoIaddaandbthenreturnthemrdquo

4PythonaddsthetwonumbersThenwhenthefunctionendsanylinethatrunsitwillbeabletoassignthisa+bresulttoavariable

AswithmanyotherthingsinthisbookyoushouldtakethisrealslowbreakitdownandtrytotracewhatrsquosgoingonTohelpthereisextracredittosolveapuzzleandlearnsomethingcool

WhatYouShouldSeeClickheretoviewcodeimage

Exercise21Session

$python36ex21py

Letsdosomemathwithjustfunctions

ADDING30+5

SUBTRACTING78-4

MULTIPLYING902

DIVIDING1002

Age35Height74Weight180IQ500

Hereisapuzzle

DIVIDING5002

MULTIPLYING180250

SUBTRACTING74-45000

ADDING35+-44260

Thatbecomes-43910Canyoudoitbyhand

StudyDrills1IfyouarenrsquotreallysurewhatreturndoestrywritingafewofyourownfunctionsandhavethemreturnsomevaluesYoucanreturnanythingthatyoucanputtotherightofan=

2AttheendofthescriptisapuzzleIrsquomtakingthereturnvalueofonefunctionandusingitastheargumentofanotherfunctionIrsquomdoingthisinachainsothatIrsquomkindofcreatingaformulausingthefunctionsItlooks

reallyweirdbutifyourunthescriptyoucanseetheresultsWhatyoushoulddoistrytofigureoutthenormalformulathatwouldrecreatethissamesetofoperations

3OnceyouhavetheformulaworkedoutforthepuzzlegetinthereandseewhathappenswhenyoumodifythepartsofthefunctionsTrytochangeitonpurposetomakeanothervalue

4DotheinverseWriteasimpleformulaandusethefunctionsinthesamewaytocalculateit

ThisexercisemightreallywhackyourbrainoutbuttakeitslowandeasyandtreatitlikealittlegameFiguringoutpuzzleslikethisiswhatmakesprogrammingfunsoIrsquollbegivingyoumorelittleproblemslikethisaswego

CommonStudentQuestionsWhydoesPythonprinttheformulaorthefunctionsldquobackwardrdquoItrsquosnotreallybackwarditrsquosldquoinsideoutrdquoWhenyoustartbreakingdownthefunctionintoseparateformulasandfunctioncallsyoursquollseehowitworksTrytounderstandwhatImeanbyldquoinsideoutrdquoratherthanldquobackwardrdquo

HowcanIuseinput()toentermyownvaluesRememberint(input())Theproblemwiththatisthenyoucanrsquotenterfloatingpointsoalsotryusingfloat(input())instead

WhatdoyoumeanbyldquowriteoutaformulardquoTry24+34100-1023asastartConvertthattousethefunctionsNowcomeupwithyourownsimilarmathequationandusevariablessoitrsquosmorelikeaformula

Exercise22WhatDoYouKnowSoFar

TherewonrsquotbeanycodeinthisexerciseorthenextonesotherersquosnoWhatYouShouldSeeorStudyDrillssectionsInfactthisexerciseislikeonegiantStudyDrillsIrsquomgoingtohaveyoudoareviewofwhatyouhavelearnedsofarFirstgobackthrougheveryexerciseyouhavedonesofarandwritedowneverywordandsymbol(anothernameforldquocharacterrdquo)thatyouhaveusedMakesureyourlistofsymbolsiscompleteNexttoeachwordorsymbolwriteitsnameandwhatitdoesIfyoucanrsquotfindanameforasymbolinthisbookthenlookforitonlineIfyoudonotknowwhatawordorsymboldoesthenreadaboutitagainandtryusingitinsomecodeYoumayrunintoafewthingsyoucanrsquotfindoutorknowsojustkeepthoseonthelistandbereadytolookthemupwhenyoufindthemOnceyouhaveyourlistspendafewdaysrewritingthelistanddouble-checkingthatitrsquoscorrectThismaygetboringbutpushthroughandreallynailitdownOnceyouhavememorizedthelistandwhattheydothenstepitupbywritingouttablesofsymbolstheirnamesandwhattheydofrommemoryIfyouhitsomeyoucanrsquotrecallfrommemorygobackandmemorizethemagain

WarningThemostimportantthingwhendoingthisexerciseisldquoThereisnofailureonlytryingrdquo

WhatYouAreLearningItrsquosimportantwhenyouaredoingaboringmindlessmemorizationexerciselikethistoknowwhyIthelpsyoufocusonagoalandknowthepurposeofallyoureffortsInthisexerciseyouarelearningthenamesofsymbolssothatyoucanreadsourcecodemoreeasilyItrsquossimilartolearningthealphabetandbasicwordsofEnglishexceptthisPythonalphabethasextrasymbolsyoumightnotknowJusttakeitslowanddonothurtyourbrainItrsquosbesttotake15minutesatatimewithyourlistandthentakeabreakGivingyourbrainarestwillhelpyoulearnfasterwithlessfrustration

Exercise23StringsBytesandCharacterEncodings

TodothisexerciseyoursquollneedtodownloadatextfilethatIrsquovewrittennamedlanguagestxt(httpslearnpythonthehardwayorgpython3languagestxt)Thisfilewascreatedwithalistofhumanlanguagestodemonstrateafewinterestingconcepts

1HowmoderncomputersstorehumanlanguagesfordisplayandprocessingandhowPython3callsthisstrings

2HowyoumustldquoencoderdquoandldquodecoderdquoPythonrsquosstringsintoatypecalledbytes

3Howtohandleerrorsinyourstringandbytehandling4Howtoreadcodeandfindoutwhatitmeansevenifyoursquoveneverseenitbefore

InadditiontothatyoursquollalsogetabriefglimpseofthePython3if-statementandlistsforprocessingalistofthingsYoudonrsquothavetomasterthiscodeorunderstandtheseconceptsrightawayYoursquollgetplentyofpracticeinlaterexercisesFornowyourjobistogetatasteofthefutureandlearnthefourtopicsintheprecedinglist

WarningThisexerciseishardTherersquosalotofinformationinitthatyouneedtounderstandanditrsquosinformationthatgoesdeepintocomputersThisexerciseiscomplexbecausePythonrsquosstringsarecomplexanddifficulttouseIrecommendyoutakethisexercisepainfullyslowWritedowneverywordyoudonrsquotunderstandandlookituporresearchitTakeaparagraphatatimeifyoumustYoucancontinuewithotherexerciseswhileyoustudythisonesodonrsquotgetstuckhereJustchipawayatitforaslongasittakes

InitialResearchIrsquomgoingtoteachyouhowtoresearchapieceofcodetoexposeitssecretsYoursquollneedthelanguagestxtfileforthiscodetoworksomakesureyoudownloaditfirstThelanguagestxtfilesimplycontainsalistofhumanlanguagenamesthatareencodedinUTF-8Clickheretoviewcodeimage

ex23py

1importsys

2scriptencodingerror=sysargv

3

4

5defmain(language_fileencodingerrors)

6line=language_filereadline()

7

8ifline

9print_line(lineencodingerrors)

10returnmain(language_fileencodingerrors)

11

12

13defprint_line(lineencodingerrors)

14next_lang=linestrip()

15raw_bytes=next_langencode(encodingerrors=errors)

16cooked_string=raw_bytesdecode(encodingerrors=errors)

17

18print(raw_byteslt===gtcooked_string)

19

20

21languages=open(languagestxtencoding=utf-8)

22

23main(languagesencodingerror)

SimplywritedownalistofeachthingyoursquoveneverseenbeforeTheremaybequiteafewthingsthatarenewsoscanthefileafewtimesOnceyouhavethatyoursquollwanttorunthisPythonscripttoplaywithitHerearesomeexamplecommandsIusedtotestit

WarningYoursquollnoticeIrsquomusingimagesheretoshowyouwhatyoushouldseeAfterextensivetestingitturnsoutthatsomanypeoplehave

seeAfterextensivetestingitturnsoutthatsomanypeoplehavetheircomputersconfiguredtonotdisplayUTF-8thatIhadtouseimagessoyoursquollknowwhattoexpectEvenmyowntypesettingsystem(LaTeX)couldnrsquothandletheseencodingsforcingmetouseimagesinsteadIfyoudonrsquotseethisthenyourTerminalismostlikelynotabletodisplayUTF-8andyoushouldtrytofixthat

Theseexamplesusetheutf-8utf-16andbig5encodingstodemonstratetheconversionandthetypesoferrorsyoucangetEachofthesenamesarecalledaldquocodecrdquoinPython3butyouusetheparameterldquoencodingrdquoAttheendofthisexercisetherersquosalistoftheavailableencodingsifyouwanttotrymoreIrsquollcoverwhatallofthisoutputmeansshortlyYoursquoreonlytryingtogetanideaofhowthisworkssowecantalkaboutitAfteryoursquoverunitafewtimesgothroughyourlistofsymbolsandmakeaguessastowhattheydoWhenyoursquovewrittendownyourguessestrylookingthesymbolsuponlinetoseeifyoucanconfirmyourhypothesesDonrsquotworryifyouhavenoideahowtosearchforthemJustgiveitatry

SwitchesConventionsandEncodingsBeforeIcangetintowhatthiscodemeansyouneedtolearnsomebasicsabouthowdataisstoredinacomputerModerncomputersareincrediblycomplexbutattheircorestheyarelikeahugearrayoflightswitchesComputersuseelectricitytoflipswitchesonoroffTheseswitchescanrepresent1foronor0foroffIntheolddaystherewereallkindsofweirdcomputersthatdidmorethanjust1or0butthesedaysitrsquosjust1sand0sOnerepresentsenergyelectricityonpowersubstanceZerorepresentsoffdonegonepowerdownthelackofenergyWecallthese1sand0sldquobitsrdquoNowacomputerthatonlyletsyouworkwith1and0wouldbebothhorriblyinefficientandincrediblyannoyingComputerstakethese1sand0sandusethemtoencodelargernumbersAtthesmallendacomputerwilluse8ofthese1sand0stoencode256numbers(0-255)WhatdoesldquoencoderdquomeanthoughItrsquosnothingmorethananagreed-uponstandardforhowasequenceofbitsshouldrepresentanumberItrsquosaconventionhumanspickedorstumbledonthatsaysthat00000000wouldbe011111111wouldbe255and00001111wouldbe15TherewereevenhugewarsintheearlyhistoryofcomputersonnothingmorethantheorderofthesebitsbecausetheyweresimplyconventionsweallhadtoagreeonTodaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryone

Todaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryonehadtheirownconventionforabytesoyoursquollstillrunintopeoplewhothinkthatthistermshouldbeflexibleandhandlesequencesof9bits7bitsor6bitsbutnowwejustsayitrsquos8bitsThatrsquosourconventionandthatconventiondefinesourencodingforabyteTherearefutherconventionsforencodinglargenumbersusing163264andevenmorebitsifyougetintoreallybigmathTherersquosentirestandardsgroupswhodonothingbutargueabouttheseconventionsthenimplementthemasencodingsthateventuallyturnswitchesonandoffOnceyouhavebytesyoucanstarttostoreanddisplaytextbydecidingonanotherconventionforhowanumbermapstoaletterIntheearlydaysofcomputingthereweremanyconventionsthatmapped8or7bits(orlessormore)ontolistsofcharacterskeptinsideacomputerThemostpopularconventionendedupbeingAmericanStandardCodeforInformationInterchangeorASCIIThisstandardmapsanumbertoaletterThenumber90isZwhichinbitsis1011010whichgetsmappedtotheASCIItableinsidethecomputerYoucantrythisoutinPythonrightnow

gtgtgt0b1011010

90

gtgtgtord(Z)

90

gtgtgtchr(90)

Z

gtgtgt

FirstIwritethenumber90inbinarythenIgetthenumberbasedontheletterZthenIconvertthenumbertotheletterZDonrsquotworryaboutneedingtorememberthisthoughIthinkIrsquovehadtodoittwicetheentiretimeIrsquoveusedPythonOncewehavetheASCIIconventionforencodingacharacterusing8bits(abyte)wecanthenldquostringrdquothemtogethertomakeawordIfIwanttowritemynameldquoZedAShawrdquoIjustuseasequenceofbytes[90101100326546328310497119]MostoftheearlytextincomputerswasnothingmorethansequencesofbytesstoredinmemorythatacomputerusedtodisplaytexttoapersonAgainthisisjustasequenceofconventionsthatturnedswitchesonandoffTheproblemwithASCIIisthatitonlyencodesEnglishandmaybeafewothersimilarlanguagesRememberthatabytecanhold256numbers(0-255or

00000000-11111111)Turnsouttherersquosalotmorecharactersthan256usedthroughouttheworldrsquoslanguagesDifferentcountriescreatedtheirownencodingconventionsfortheirlanguagesandthatmostlyworkedbutmanyencodingscouldonlyhandleonelanguageThatmeantifyouwanttoputthetitleofanAmericanEnglishbookinthemiddleofaThaisentenceyouwerekindofintroubleYoursquodneedoneencodingforThaiandoneforEnglishTosolvethisproblemagroupofpeoplecreatedUnicodeItsoundslikeldquoencoderdquoanditismeanttobealdquouniversalencodingrdquoofallhumanlanguagesThesolutionUnicodeprovidesisliketheASCIItablebutitrsquoshugebycomparisonYoucanuse32bitstoencodeaUnicodecharacterandthatismorecharactersthanwecouldpossiblyfindA32-bitnumbermeanswecanstore4294967295characters(2^32)whichisenoughspaceforeverypossiblehumanlanguageandprobablyalotofalienonestooRightnowweusetheextraspaceforimportantthingslikepoopandsmileemojisWenowhaveaconventionforencodinganycharacterswewantbut32bitsis4bytes(328==4)whichmeansthereissomuchwastedspaceinmosttextwewanttoencodeWecanalsouse16bits(2bytes)butstilltherersquosgoingtobewastedspaceinmosttextThesolutionistouseacleverconventiontoencodemostcommoncharactersusing8bitsandthenldquoescaperdquointolargernumberswhenweneedtoencodemorecharactersThatmeanswehaveonemoreconventionthatisnothingmorethanacompressionencodingmakingitpossibleformostcommoncharacterstouse8bitsandthenescapeoutinto16or32bitsasneededTheconventionforencodingtextinPythoniscalledldquoUTF-8rdquowhichmeansldquoUnicodeTransformationFormat8BitsrdquoItisaconventionforencodingUnicodecharactersintosequencesofbyteswhicharesequencesofbitswhichturnsequencesofswitchesonandoffYoucanalsouseotherconventions(encodings)butUTF-8isthecurrentstandard

DisectingtheOutputWecannowlookattheoutputofthecommandsshownpreviouslyLetrsquostakejustthatfirstcommandandthefirstfewlinesofoutput

Theex23pyscriptistakingbyteswritteninsidetheb(bytestring)andconvertingthemtotheUTF-8(orother)encodingyouspecifiedOntheleftisthenumbersforeachbyteoftheUTF-8(showninhexadecimal)andtherighthasthecharacteroutputasactualUTF-8Thewaytothinkofthisistheleftsideoflt===gtisthePythonnumericalbytesortheldquorawrdquobytesPythonusestostorethestringYouspecifythiswithbtotellPythonthisisbytesTheserawbytesarethendisplayedldquocookedrdquoontherightsoyoucanseetherealcharactersinyourTerminal

DisectingtheCodeWehaveanunderstandingofstringsandbytesequencesInPythonastringisaUTF-8encodedsequenceofcharactersfordisplayingorworkingwithtextThebytesarethentheldquorawrdquosequenceofbytesthatPythonusestostorethisUTF-8stringandstartwithabtotellPythonyouareworkingwithrawbytesThisisallbasedonconventionsforhowPythonwantstoworkwithtextHerersquosaPythonsessionshowingmeencodingstringsanddecodingbytes

Allyouneedtorememberisifyouhaverawbytesthenyoumustusedecode()togetthestringRawbyteshavenoconventiontothemTheyarejustsequencesofbyteswithnomeaningotherthannumberssoyoumusttellPythontoldquodecodethisintoaUTFstringrdquoIfyouhaveastringandwanttosenditstoreitshareitordosomeotheroperationthenusuallyitrsquollworkbutsometimesPythonwillthrowupanerrorsayingitdoesnrsquotknowhowtoldquoencoderdquoitAgainPythonknowsitsinternalconventionbutithasnoideawhatconventionyouneedInthatcaseyoumustuseencode()togetthebytesyouneedThewaytorememberthis(eventhoughIlookitupalmosteverytime)istorememberthemnemonicDBESwhichstandsforDecodeBytesEncodeStringsIsayldquodeebessrdquoinmyheadwhenIhavetoconvertbytesandstringsWhenyouhavebytesandneedastringdecodebytesWhenyouhaveastringandneedbytesencodestringsWiththatinmindletrsquosbreakdownthecodeinex23pyline-by-line1ndash2Istartwiththeusualcommandlineargumenthandlingthatyoualready

know5IstartthemainmeatofthiscodeinafunctionconvenientlycalledmainThiswillbecalledattheendofthisscripttogetthingsgoing

6ThefirstthingthisfunctiondoesisreadonelinefromthelanguagesfileitisgivenYouhavedonethisbeforesonothingnewhereJustreadlineasbeforewhendealingwithtextfiles

8IusesomethingnewYouwilllearnaboutthisinthesecondhalfofthebooksoconsiderthisateaserofinterestingthingstocomeThisisanif-statementanditletsyoumakedecisionsinyourPythoncodeYoucantestthetruthofavariableandbasedonthattruthrunapieceofcodeornotrunitInthiscaseIrsquomtestingwhetherlinehassomethinginitThereadlinefunctionwillreturnanemptystringwhenitreachestheendofthefileandiflinesimplytestsforthisemptystringAslongasreadlinegivesussomethingthiswillbetrueandthecodeunder(indentedinlines9ndash10)willrunWhenthisisfalsePythonwillskiplines9ndash10

9IcallaseparatefunctiontodotheactualprintingofthislineThissimplifiesmycodeandmakesiteasierformetounderstanditIfIwanttolearnwhatthisfunctiondoesIcanjumptoitandstudyOnceIknowwhatprint_linedoesIcanattachmymemorytothenameprint_line

andforgetaboutthedetails10IhavewrittenatinyyetpowerfulpieceofmagichereIamcallingmainagaininsidemainActuallyitrsquosnotmagicsincenothingreallyismagicalinprogrammingAlltheinformationyouneedisthereThislookslikeIamcallingthefunctioninsideitselfwhichseemslikeitshouldbeillegaltodoAskyourselfwhyshouldthatbeillegalTherersquosnotechnicalreasonwhyIcanrsquotcallanyfunctionIwantrightthereeventhismainfunctionIfafunctionissimplyajumptothetopwhereIrsquovenameditmainthencallingthisfunctionattheendofitselfwouldjumpbacktothetopandrunitagainThatwouldmakeitloopNowlookbackatline8andyoursquollseetheif-statementkeepsthisfunctionfromloopingforeverCarefullystudythisbecauseitisasignificantconceptbutdonrsquotworryifyoucanrsquotgraspitrightaway

13Istartthedefinitionfortheprint_linefunctionwhichdoestheactualencodingofeachlinefromthelanguagestxtfile

14Thisisasimplestrippingofthetrailingnonthelinestring15IfinallytakethelanguageIrsquovereceivedfromthelanguagestxtfileandencodeitintotherawbytesRemembertheDBESmnemonicDecodebytesencodestringsThenext_langvariableisastringsotogettherawbytesImustcallencode()onittoencodestringsIpasstoencode()theencodingIwantandhowtohandleerrors

16Idotheextrastepofshowingtheinverseofline15bycreatingacooked_stringvariablefromtheraw_bytesRememberDBESsaysIdecodebytesandraw_bytesisbytessoIcalldecode()onittogetaPythonstringThisstringshouldbethesameasthenext_langvariable

18Isimplyprintthembothouttoshowyouwhattheylooklike21IrsquomdonedefiningfunctionssonowIwanttoopenthelanguagestxtfile

23Theendofthescriptsimplyrunsthemainfunctionwithallthecorrectparameterstogeteverythinggoingandkick-starttheloopRememberthatthisthenjumpstowherethemainfunctionisdefinedonline5andonline10mainiscalledagaincausingthistokeeploopingTheiflineonline8willpreventourloopfromgoingforever

EncodingsDeepDive

WecannowuseourlittlescripttoexploreotherencodingsThefollowingshowsmeplayingwithdifferentencodingsandseeinghowtobreakthemFirstIrsquomdoingasimpleUTF-16encodingsoyoucanseehowitchangescomparedtoUTF-8YoucanalsouseUTF-32toseehowthatrsquosevenbiggerandgetanideaofthespacesavedwithUTF-8AfterthatItryBig5andyoursquollseethatPythondoesnotlikethatatallItthrowsupanerrorthatBig5canrsquotencodesomeofthecharactersatposition0(whichissuperhelpful)OnesolutionistotellPythontoldquoreplacerdquoanybadcharactersfortheBig5encodingThatrsquosthenextexampleandyoursquollseeitputsacharacterwhereveritfindsacharacterthatdoesnrsquotmatchtheBig5encodingsystem

BreakingItRoughideasincludethefollowing

1Findstringsoftextencodedinotherencodingsandplacethemintheex23pyfiletoseehowitbreaks

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist3ExtrachallengingRewritethisusingthebbytesinsteadoftheUTF-8stringseffectivelyreversingthescript

4IfyoucandothatthenyoucanalsobreakthesebytesbyremovingsometoseewhathappensHowmuchdoyouneedtoremovetocausePythontobreakHowmuchcanyouremovetodamagethestringoutputbutpassPythonrsquosdecodingsystem

5Usewhatyoulearnedfromitem4toseeifyoucanmanglethefilesWhaterrorsdoyougetHowmuchdamagecanyoucauseandgetthefilepastPythonrsquosdecodingsystem

Exercise24MorePractice

YouaregettingtotheendofthissectionYoushouldhaveenoughPythonldquounderyourfingersrdquotomoveontolearningabouthowprogrammingreallyworksbutyoushoulddosomemorepracticeThisexerciseislongerandallaboutbuildingupstaminaThenextexercisewillbesimilarDothemgetthemexactlyrightanddoyourchecksClickheretoviewcodeimage

ex24py

1print(Letspracticeeverything)

2print(Youdneedtoknowboutescapeswiththatdo)

3print(nnewlinesandttabs)

4

5poem=

6tThelovelyworld

7withlogicsofirmlyplanted

8cannotdiscernntheneedsoflove

9norcomprehendpassionfromintuition

10andrequiresanexplanation

11nttwherethereisnone

12

13

14print(--------------)

15print(poem)

16print(--------------)

17

18

19five=10-2+3-6

20print(fThisshouldbefivefive)

21

22defsecret_formula(started)

23jelly_beans=started500

24jars=jelly_beans1000

25crates=jars100

26returnjelly_beansjarscrates

27

28

29start_point=10000

30beansjarscrates=secret_formula(start_point)

31

32rememberthatthisisanotherwaytoformatastring

33print(Withastartingpointofformat(start_point))

34itsjustlikewithanfstring

35print(fWedhavebeansbeansjarsjarsandcrates

crates)

36

37start_point=start_point10

38

39print(Wecanalsodothatthisway)

40formula=secret_formula(start_point)

41thisisaneasywaytoapplyalisttoaformatstring

42print(Wedhavebeansjarsand

cratesformat(formula))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise24Session

$python36ex24py

Letspracticeeverything

Youdneedtoknowboutescapeswiththatdo

newlinesandtabs

--------------

Thelovelyworld

withlogicsofirmlyplanted

cannotdiscern

theneedsoflove

norcomprehendpassionfromintuition

andrequiresanexplanation

wherethereisnone

--------------

Thisshouldbefive5

Withastartingpointof10000

Wedhave5000000beans50000jarsand500crates

Wecanalsodothatthisway

Wedhave5000000beans5000jarsand50crates

StudyDrills1Makesuretodoyourchecksreaditbackwardreaditoutloudandputcommentsaboveconfusingparts

2BreakthefileonpurposethenrunittoseewhatkindsoferrorsyougetMakesureyoucanfixit

CommonStudentQuestionsWhydoyoucallthevariablejelly_beansbutthenamebeanslaterThatrsquospartofhowafunctionworksRememberthatinsidethefunctionthevariableistemporaryWhenyoureturnitthenitcanbeassignedtoavariableforlaterIrsquomjustmakinganewvariablenamedbeanstoholdthereturnvalue

WhatdoyoumeanbyreadingthecodebackwardStartatthelastlineComparethatlineinyourfiletothesamelineinmineOnceitrsquosexactlythesamemoveuptothenextlineDothisuntilyougettothefirstlineofthefile

WhowrotethatpoemIdidNotallofmypoemssuck

Exercise25EvenMorePractice

WersquoregoingtodosomemorepracticeinvolvingfunctionsandvariablestomakesureyouknowthemwellThisexerciseshouldbestraightforwardforyoutotypeinbreakdownandunderstandHoweverthisexerciseisalittledifferentYouwonrsquotberunningitInsteadyouwillimportitintoPythonandrunthefunctionsyourselfClickheretoviewcodeimage

ex25py

1defbreak_words(stuff)

2Thisfunctionwillbreakupwordsforus

3words=stuffsplit()

4returnwords

5

6defsort_words(words)

7Sortsthewords

8returnsorted(words)

9

10defprint_first_word(words)

11Printsthefirstwordafterpoppingitoff

12word=wordspop(0)

13print(word)

14

15defprint_last_word(words)

16Printsthelastwordafterpoppingitoff

17word=wordspop(-1)

18print(word)

19

20defsort_sentence(sentence)

21Takesinafullsentenceandreturnsthesorted

words

22words=break_words(sentence)

23returnsort_words(words)

24

25defprint_first_and_last(sentence)

26Printsthefirstandlastwordsofthesentence

27words=break_words(sentence)

28print_first_word(words)

29print_last_word(words)

30

31defprint_first_and_last_sorted(sentence)

32Sortsthewordsthenprintsthefirstandlastone

33words=sort_sentence(sentence)

34print_first_word(words)

35print_last_word(words)Firstrunthiswithpython36

ex25pytofindanyerrorsyouhavemadeOnceyouhavefoundallof

theerrorsyoucanandfixedthemyouwillthenwanttofollowthe

WhatYouShouldSeesectiontocompletetheexercise

WhatYouShouldSeeInthisexercisewersquoregoingtointeractwithyourex25pyfileinsidethepython36interpreteryouusedperiodicallytodocalculationsYourunpython36fromtheTerminallikethisClickheretoviewcodeimage

$python36

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtYouroutputshouldlooklikemineandafterthegtcharacter

(calledtheprompt)youcantypePythoncodeinanditwillrun

immediatelyUsingthisIwantyoutotypeeachoftheselinesof

Pythoncodeintopython36andseewhatitdoesClickheretoview

codeimage

Exercise25PythonSession

1importex25

2sentence=Allgoodthingscometothosewhowait

3words=ex25break_words(sentence)

4words

5sorted_words=ex25sort_words(words)

6sorted_words

7ex25print_first_word(words)

8ex25print_last_word(words)

9words

10ex25print_first_word(sorted_words)

11ex25print_last_word(sorted_words)

12sorted_words

13sorted_words=ex25sort_sentence(sentence)

14sorted_words

15ex25print_first_and_last(sentence)

16ex25print_first_and_last_sorted(sentence)Herersquoswhatitlooks

likewhenIworkwiththeex25pymoduleinpython36Clickhereto

viewcodeimage

Exercise25PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtimportex25

gtgtgtsentence=Allgoodthingscometothosewhowait

gtgtgtwords=ex25break_words(sentence)

gtgtgtwords

[Allgoodthingscometothosewhowait]

gtgtgtsorted_words=ex25sort_words(words)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_word(words)

All

gtgtgtex25print_last_word(words)

wait

gtgtgtwords

[goodthingscometothosewho]

gtgtgtex25print_first_word(sorted_words)

All

gtgtgtex25print_last_word(sorted_words)

who

gtgtgtsorted_words

[comegoodthingsthosetowait]

gtgtgtsorted_words=ex25sort_sentence(sentence)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_and_last(sentence)

All

wait

gtgtgtex25print_first_and_last_sorted(sentence)

All

whoAsyougothrougheachoftheselinesmakesureyoucanfindthe

functionthatrsquosbeingruninex25pyandunderstandhoweachone

worksIfyougetdifferentresultsorerroryoursquollhavetogofix

yourcodeexitpython36andstartover

StudyDrills1TaketheremaininglinesoftheWhatYouShouldSeeoutputandfigureoutwhattheyaredoingMakesureyouunderstandhowyouarerunningyourfunctionsintheex25module

2Trydoingthishelp(ex25)andalsohelp(ex25break_words)Noticehowyougethelpforyourmoduleandhowthehelpisthoseoddstringsyouputaftereachfunctioninex25Thosespecialstringsarecalleddocumentationcommentsandwersquollbeseeingmoreofthem

3Typingex25isannoyingAshortcutistodoyourimportlikethisfromex25importThisislikesayingldquoImporteverythingfromex25rdquoProgrammerslikesayingthingsbackwardStartanewsessionandseehowallyourfunctionsarerightthere

4TrybreakingyourfileandseewhatitlookslikeinpythonwhenyouuseitYouwillhavetoquitpythonwithquit()tobeabletoreloadit

CommonStudentQuestionsIgetNoneprintedoutforsomeofthefunctionsYouprobablyhaveafunctionthatismissingthereturnattheendGobackwardthroughthefileandconfirmthateverylineisright

Iget-bashimportcommandnotfoundwhenItypeimportex25PayattentiontowhatIrsquomdoingintheWhatYouShouldSeesectionIrsquomdoingthisinPythonnotintheTerminalThatmeansyoufirstrunPython

IgetImportErrorNomodulenamedex25pywhenItypeimportex25pyDonrsquotaddthepytotheendPythonknowsthefileendsinpysoyoujusttypeimportex25

IgetSyntaxErrorinvalidsyntaxwhenIrunthisThatmeansyouhavesomethinglikeamissing(ororsimilarsyntaxerroronthatlineoraboveitAnytimeyougetthaterrorstartatthelineitmentionsandcheckthatitrsquosrightthengobackwardcheckingeachlineabovethat

HowcanthewordspopfunctionchangethewordsvariableThatrsquosacomplicatedquestionbutinthiscasewordsisalistandbecauseofthatyoucangiveitcommandsanditrsquollretaintheresultsofthosecommandsThisissimilartohowfilesandmanyotherthingsworkedwhenyouwereworkingwiththem

WhenshouldIprintinsteadofreturninafunctionThereturnfromafunctiongivesthelineofcodethatcalledthefunctionaresultYoucanthinkofafunctionastakinginputthroughitsargumentsandreturningoutputthroughreturnTheprintiscompletelyunrelatedtothisandonlydealswithprintingoutputtotheTerminal

Exercise26CongratulationsTakeaTest

YouarealmostdonewiththefirsthalfofthebookThesecondhalfiswherethingsgetinterestingYouwilllearnlogicandbeabletodousefulthingslikemakedecisionsBeforeyoucontinueIhaveaquizforyouThisquizwillbeveryhardbecauseitrequiresyoutofixsomeoneelsersquoscodeWhenyouareaprogrammeryouoftenhavetodealwithotherprogrammersrsquocodemdashandalsowiththeirarroganceProgrammerswillveryfrequentlyclaimthattheircodeisperfectTheseprogrammersarestupidpeoplewhocarelittleforothersAgoodprogrammerassumeslikeagoodscientistthattherersquosalwayssomeprobabilitytheircodeiswrongGoodprogrammersstartfromthepremisethattheirsoftwareisbrokenandthenworktoruleoutallpossiblewaysitcouldbewrongbeforefinallyadmittingthatmaybeitreallyistheotherguyrsquoscodeInthisexerciseyouwillpracticedealingwithabadprogrammerbyfixingabadprogrammerrsquoscodeIhavepoorlycopiedExercises24and25intoafileandremovedrandomcharactersandaddedflawsMostoftheerrorsarethingsPythonwilltellyouwhilesomeofthemarematherrorsyoushouldfindOthersareformattingerrorsorspellingmistakesinthestringsAlloftheseerrorsareverycommonmistakesallprogrammersmakemdashevenexperiencedonesYourjobinthisexerciseistocorrectthisfileUseallofyourskillstomakethisfilebetterAnalyzeitfirstmaybeprintingitouttoedititlikeyouwouldaschooltermpaperFixeachflawandkeeprunningitandfixingituntilthescriptrunsperfectlyTrynottogethelpIfyougetstucktakeabreakandcomebacktoitlaterEvenifthistakesdaystodobustthroughitandmakeitrightThepointofthisexerciseisnrsquottotypeitinbuttofixanexistingfileTodothatyoumustgotohttplearnpythonthehardwayorgpython3exercise26txtCopy-pastethecodeintoafilenamedex26pyThisistheonlytimeyouareallowedtocopy-paste

CommonStudentQuestionsDoIhavetoimportex25pyorcanIjustremovethereferencestoitYoucandoeitherThisfilehasthefunctionsfromex25

thoughsofirstgowithremovingreferencestoitCanIrunthecodewhileIrsquomfixingitYoumostcertainlymayThecomputeristheretohelpsouseitasmuchaspossible

Exercise27MemorizingLogic

TodayisthedayyoustartlearningaboutlogicUptothispointyouhavedoneeverythingyoupossiblycanreadingandwritingfilestotheTerminalandhavelearnedquitealotofthemathcapabilitiesofPythonFromnowonyouwillbelearninglogicYouwonrsquotlearncomplextheoriesthatacademicslovetostudybutjustthebasiclogicthatmakesrealprogramsworkandthatrealprogrammersneedeverydayLearninglogichastocomeafteryoudosomememorizationIwantyoutodothisexerciseforanentireweekDonotfalterEvenifyouareboredoutofyourmindkeepdoingitThisexercisehasasetoflogictablesyoumustmemorizetomakeiteasierforyoutodothelaterexercisesIrsquomwarningyouthiswonrsquotbefunatfirstItwillbedownrightboringandtediousbutthisteachesyouaveryimportantskillyouwillneedasaprogrammerYouwillneedtobeabletomemorizeimportantconceptsinyourlifeMostoftheseconceptswillbeexcitingonceyougetthemYouwillstrugglewiththemlikewrestlingasquidthenonedayyouwillunderstanditAllthatworkmemorizingthebasicspaysoffbiglaterHerersquosatiponhowtomemorizesomethingwithoutgoinginsaneDoatinybitatatimethroughoutthedayandmarkdownwhatyouneedtoworkonmostDonottrytositdownfortwohoursstraightandmemorizethesetablesThiswonrsquotworkYourbrainwillonlyretainwhateveryoustudiedinthefirst15or30minutesanywayInsteadcreateabunchofindexcardswitheachcolumnontheleft(TrueorFalse)onthefrontandthecolumnontherightonthebackYoushouldthentakethemoutseetheldquoTrueorFalserdquoandimmediatelysayldquoTruerdquoKeeppracticinguntilyoucandothisOnceyoucandothatstartwritingoutyourowntruthtableseachnightintoanotebookDonotjustcopythemTrytodothemfrommemoryWhenyougetstuckglancequicklyattheonesIhaveheretorefreshyourmemoryDoingthiswilltrainyourbraintorememberthewholetableDonotspendmorethanoneweekonthisbecauseyouwillbeapplyingitasyougo

TheTruthTermsInPythonwehavethefollowingterms(charactersandphrases)fordeterminingifsomethingisldquoTruerdquoorldquoFalserdquoLogiconacomputerisallaboutseeingifsomecombinationofthesecharactersandsomevariablesisTrueatthatpointin

somecombinationofthesecharactersandsomevariablesisTrueatthatpointintheprogram

bullandbullorbullnotbull=(notequal)bull==(equal)bullgt=(greater-than-equal)bulllt=(less-than-equal)bullTruebullFalse

YouactuallyhaverunintothesecharactersbeforebutmaybenotthetermsTheterms(andornot)actuallyworkthewayyouexpectthemtojustlikeinEnglish

TheTruthTablesWewillnowusethesecharacterstomakethetruthtablesyouneedtomemorize

NowusethesetablestowriteupyourowncardsandspendtheweekmemorizingthemRememberthoughthereisnofailinginthisbookjusttryingashardasyoucaneachdayandthenalittlebitmore

CommonStudentQuestionsCanrsquotIjustlearntheconceptsbehindBooleanalgebraandnotmemorizethisSureyoucandothatbutthenyoursquollhavetoconstantlygothroughtherulesforBooleanalgebrawhileyoucodeIfyoumemorizethesefirstitnotonlybuildsyourmemorizationskillsitalsomakestheseoperationsnaturalAfterthattheconceptofBooleanalgebraiseasyButdowhateverworksforyou

Exercise28BooleanPractice

ThelogiccombinationsyoulearnedfromthelastexercisearecalledBooleanlogicexpressionsBooleanlogicisusedeverywhereinprogrammingItisafundamentalpartofcomputationandknowingtheexpressionsisakintoknowingyourscalesinmusicInthisexerciseyouwilltakethelogicexercisesyoumemorizedandstarttryingthemoutinPythonTakeeachoftheselogicproblemsandwritewhatyouthinktheanswerwillbeIneachcaseitwillbeeitherTrueorFalseOnceyouhavetheanswerswrittendownstartPythoninyourTerminalandtypeeachlogicproblemintoconfirmyouranswers

1TrueandTrue2FalseandTrue31==1and2==14test==test51==1or2=16Trueand1==17Falseand0=08Trueor1==19test==testing101=0and2==111test=testing12test==113not(TrueandFalse)14not(1==1and0=1)15not(10==1or1000==1000)16not(1=10or3==4)17not(testing==testingandZed==CoolGuy)

181==1and(not(testing==1or1==0))19chunky==baconand(not(3==4or3==3))203==3and(not(testing==testingor

Python==Fun))

IwillalsogiveyouatricktohelpyoufigureoutthemorecomplicatedonestowardtheendWheneveryouseetheseBooleanlogicstatementsyoucansolvethemeasilybythissimpleprocess1Findanequalitytest(==or=)andreplaceitwithitstruth

2Findeachandorinsideparenthesesandsolvethosefirst3Findeachnotandinvertit4Findanyremainingandorandsolveit5WhenyouaredoneyoushouldhaveTrueorFalse

Iwilldemonstratewithavariationonitem20Clickheretoviewcodeimage

3=4andnot(testing=testorPython==Python)

HerersquosmegoingthrougheachofthestepsandshowingyouthetranslationuntilIrsquoveboileditdowntoasingleresult1Solveeachequalitytest

3=4isTrueTrueandnot(testing=testorPython==Python)

testing=testisTrueTrueandnot(TrueorPython==Python)

Python==PythonTrueandnot(TrueorTrue)2Findeachandorinparentheses()(TrueorTrue)isTrueTrueandnot(True)

3Findeachnotandinvertitnot(True)isFalseTrueandFalse4FindanyremainingandorsandsolvethemTrueandFalseisFalse

WiththatwersquoredoneandknowtheresultisFalse

WarningThemorecomplicatedonesmayseemveryhardatfirstYoushouldbeabletotakeagoodfirststabatsolvingthembutdonotgetdiscouragedIrsquomjustgettingyouprimedformoreoftheseldquologicgymnasticsrdquosothatlatercoolstuffismucheasierJuststickwithitandkeeptrackofwhatyougetwrongbutdonotworrythatitrsquosnotgettinginyourheadquiteyetItrsquollcome

WhatYouShouldSeeAfteryouhavetriedtoguessatthesethisiswhatyoursessionwithPythonmightlooklikeClickheretoviewcodeimage

$python36

Python251(r25154863Feb62009190212)

[GCC401(AppleIncbuild5465)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtTrueandTrue

True

gtgtgt1==1and2==2

True

StudyDrills1TherearealotofoperatorsinPythonsimilarto=and==TrytofindasmanyldquoequalityoperatorsrdquoasyoucanTheyshouldbelikeltorlt=

2WriteoutthenamesofeachoftheseequalityoperatorsForexampleIcall=ldquonotequalrdquo

3PlaywithPythonbytypingoutnewBooleanoperatorsandbeforeyoupressEntertrytoshoutoutwhatitisDonotthinkaboutitShoutthefirstthingthatcomestomindWriteitdownthenpressEnterandkeeptrackofhowmanyyougetrightandwrong

4Throwawaythepieceofpaperfrom3soyoudonotaccidentallytrytouseitlater

CommonStudentQuestionsWhydoestestandtestreturntestor1and1return1insteadofTruePythonandmanylanguagesliketoreturnoneoftheoperandstotheirBooleanexpressionsratherthanjustTrueorFalseThismeansthatifyoudidFalseand1yougetthefirstoperand(False)butifyoudoTrueand1yougetthesecond(1)Playwiththisabit

Isthereanydifferencebetween=andltgtPythonhasdeprecatedltgtinfavorof=souse=Otherthanthatthereshouldbenodifference

IsnrsquotthereashortcutYesAnyandexpressionthathasaFalseisimmediatelyFalsesoyoucanstopthereAnyorexpressionthathasaTrueisimmediatelyTruesoyoucanstopthereButmakesurethatyoucanprocessthewholeexpressionbecauselateritbecomeshelpful

Exercise29WhatIf

HereisthenextscriptofPythonyouwillenterwhichintroducesyoutotheif-statementTypethisinmakeitrunexactlyrightandthenwersquollseeifyourpracticehaspaidoffClickheretoviewcodeimage

ex29py

1people=20

2cats=30

3dogs=15

4

5

6ifpeopleltcats

7print(ToomanycatsTheworldisdoomed)

8

9ifpeoplegtcats

10print(NotmanycatsTheworldissaved)

11

12ifpeopleltdogs

13print(Theworldisdrooledon)

14

15ifpeoplegtdogs

16print(Theworldisdry)

17

18

19dogs+=5

20

21ifpeoplegt=dogs

22print(Peoplearegreaterthanorequaltodogs)

23

24ifpeoplelt=dogs

25print(Peoplearelessthanorequaltodogs)

26

27

28ifpeople==dogs

29print(Peoplearedogs)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise29Session

$python36ex29py

ToomanycatsTheworldisdoomed

Theworldisdry

Peoplearegreaterthanorequaltodogs

Peoplearelessthanorequaltodogs

Peoplearedogs

StudyDrillsInthisStudyDrilltrytoguesswhatyouthinktheif-statementisandwhatitdoesTrytoanswerthesequestionsinyourownwordsbeforemovingontothenextexercise

1Whatdoyouthinktheifdoestothecodeunderit2Whydoesthecodeundertheifneedtobeindentedfourspaces3Whathappensifitisnrsquotindented4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryit

5Whathappensifyouchangetheinitialvaluesforpeoplecatsanddogs

CommonStudentQuestionsWhatdoes+=meanThecodex+=1isthesameasdoingx=x+1butinvolveslesstypingYoucancallthistheldquoincrementbyrdquooperatorThesamegoesfor-=andmanyotherexpressionsyoursquolllearnlater

Exercise30ElseandIf

Inthelastexerciseyouworkedoutsomeif-statementsandthentriedtoguesswhattheyareandhowtheyworkBeforeyoulearnmoreIrsquollexplainwhateverythingisbyansweringthequestionsyouhadfromthepreviousStudyDrillssectionYoudidtheStudyDrillsright

1WhatdoyouthinktheifdoestothecodeunderitAnif-statementcreateswhatiscalledaldquobranchrdquointhecodeItrsquoskindoflikethosechooseyourownadventurebookswhereyouareaskedtoturntoonepageifyoumakeonechoiceandanotherifyougoadifferentdirectionTheif-statementtellsyourscriptldquoIfthisBooleanexpressionisTruethenrunthecodeunderitotherwiseskipitrdquo

2WhydoesthecodeundertheifneedtobeindentedfourspacesAcolonattheendofalineishowyoutellPythonyouaregoingtocreateanewldquoblockrdquoofcodeandthenindentingfourspacestellsPythonwhatlinesofcodeareinthatblockThisisexactlythesamethingyoudidwhenyoumadefunctionsinthefirsthalfofthebook

3WhathappensifitisnrsquotindentedIfitisnrsquotindentedyouwillmostlikelycreateaPythonerrorPythonexpectsyoutoindentsomethingafteryouendalinewitha(colon)

4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryitYesyoucanandtheycanbeascomplexasyoulikealthoughreallycomplexthingsgenerallyarebadstyle

5WhathappensifyouchangetheinitialvaluesforpeoplecatsanddogsBecauseyouarecomparingnumbersifyouchangethenumbersdifferentif-statementswillevaluatetoTrueandtheblocksofcodeunderthemwillrunGobackandputdifferentnumbersinandseeifyoucanfigureoutinyourheadwhichblocksofcodewillrun

ComparemyanswerstoyouranswersandmakesureyoureallyunderstandtheconceptofaldquoblockrdquoofcodeThisisimportantforwhenyoudothenextexercisewhereyouwriteallthepartsofif-statementsthatyoucanuseTypethisoneinandmakeitworktooClickheretoviewcodeimage

ex30py

1people=30

2cars=40

3trucks=15

4

5

6ifcarsgtpeople

7print(Weshouldtakethecars)

8elifcarsltpeople

9print(Weshouldnottakethecars)

10else

11print(Wecantdecide)

12

13iftrucksgtcars

14print(Thatstoomanytrucks)

15eliftrucksltcars

16print(Maybewecouldtakethetrucks)

17else

18print(Westillcantdecide)

19

20ifpeoplegttrucks

21print(Alrightletsjusttakethetrucks)

22else

23print(Fineletsstayhomethen)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise30Session

$python36ex30py

Weshouldtakethecars

Maybewecouldtakethetrucks

Alrightletsjusttakethetrucks

StudyDrills1Trytoguesswhatelifandelsearedoing2Changethenumbersofcarspeopleandtrucksandthentracethrougheachif-statementtoseewhatwillbeprinted

3TrysomemorecomplexBooleanexpressionslikecarsgtpeopleortrucksltcars

4Aboveeachlinewriteacommentdescribingwhatthelinedoes

CommonStudentQuestions

CommonStudentQuestionsWhathappensifmultipleelifblocksareTruePythonstartsatthetopandrunsthefirstblockthatisTruesoitwillrunonlythefirstone

Exercise31MakingDecisions

InthefirsthalfofthisbookyoumostlyjustprintedoutstringsandcalledfunctionsbuteverythingwasbasicallyinastraightlineYourscriptsranstartingatthetopandwenttothebottomwheretheyendedIfyoumadeafunctionyoucouldrunthatfunctionlaterbutitstilldidnrsquothavethekindofbranchingyouneedtoreallymakedecisionsNowthatyouhaveifelseandelifyoucanstarttomakescriptsthatdecidethingsInthelastscriptyouwroteoutasimplesetoftestsaskingsomequestionsInthisscriptyouwillasktheuserquestionsandmakedecisionsbasedontheiranswersWritethisscriptandthenplaywithitquitealottofigureitoutClickheretoviewcodeimage

ex31py

1print(Youenteradarkroomwithtwodoors

2Doyougothroughdoor1ordoor2)

3

4door=input(gt)

5

6ifdoor==1

7print(Theresagiantbearhereeatingacheesecake)

8print(Whatdoyoudo)

9print(1Takethecake)

10print(2Screamatthebear)

11

12bear=input(gt)

13

14ifbear==1

15print(ThebeareatsyourfaceoffGoodjob)

16elifbear==2

17print(ThebeareatsyourlegsoffGoodjob)

18else

19print(fWelldoingbearisprobablybetter)

20print(Bearrunsaway)

21

22elifdoor==2

23print(YoustareintotheendlessabyssatCthulhus

retina)

24print(1Blueberries)

25print(2Yellowjacketclothespins)

26print(3Understandingrevolversyellingmelodies)

27

28insanity=input(gt)

29

30ifinsanity==1orinsanity==2

31print(Yourbodysurvivespoweredbyamindofjello)

32print(Goodjob)

33else

34print(Theinsanityrotsyoureyesintoapoolof

muck)

35print(Goodjob)

36

37else

38print(YoustumblearoundandfallonaknifeanddieGood

job)Akeypointhereisthatyouarenowputtingtheif-statements

insideif-statementsascodethatcanrunThisisverypowerfuland

canbeusedtocreateldquonestedrdquodecisionswhereonebranchleadsto

anotherandanother

Makesureyouunderstandthisconceptofif-statementsinsideif-statementsInfactdotheStudyDrillstoreallynailit

WhatYouShouldSeeHereismeplayingthislittleadventuregameIdonotdosowellClickheretoviewcodeimage

Exercise31Session

$python36ex31py

Youenteradarkroomwithtwodoors

Doyougothroughdoor1ordoor2

gt1

Theresagiantbearhereeatingacheesecake

Whatdoyoudo

1Takethecake

2Screamatthebear

gt2

ThebeareatsyourlegsoffGoodjob

StudyDrills1MakenewpartsofthegameandchangewhatdecisionspeoplecanmakeExpandthegameoutasmuchasyoucanbeforeitgetsridiculous

2WriteacompletelynewgameMaybeyoudonrsquotlikethisonesomakeyourownThisisyourcomputerdowhatyouwant

CommonStudentQuestions

CommonStudentQuestionsCanyoureplaceelifwithasequenceofif-elsecombinationsYoucaninsomesituationsbutitdependsonhoweachifelseiswrittenItalsomeansthatPythonwillcheckeveryif-elsecombinationratherthanjustthefirstfalseoneslikeitwouldwithif-elif-elseTrytomakesomeofthesetofigureoutthedifferences

HowdoItellwhetheranumberisbetweenarangeofnumbersYouhavetwooptionsUse0ltxlt10or1lt=xlt10whichisclassicnotationorusexinrange(110)

WhatifIwantedmoreoptionsintheif-elif-elseblocksAddmoreelifblocksforeachpossiblechoice

Exercise32LoopsandLists

YoushouldnowbeabletodosomeprogramsthataremuchmoreinterestingIfyouhavebeenkeepingupyoushouldrealizethatnowyoucancombinealltheotherthingsyouhavelearnedwithif-statementsandBooleanexpressionstomakeyourprogramsdosmartthingsHoweverprogramsalsoneedtodorepetitivethingsveryquicklyWearegoingtouseafor-loopinthisexercisetobuildandprintvariouslistsWhenyoudotheexerciseyouwillstarttofigureoutwhattheyareIwonrsquottellyourightnowYouhavetofigureitoutBeforeyoucanuseafor-loopyouneedawaytostoretheresultsofloopssomewhereThebestwaytodothisiswithlistsAlistisexactlywhatthenamesaysacontainerofthingsthatareorganizedinorderfromfirsttolastItrsquosnotcomplicatedyoujusthavetolearnanewsyntaxFirstherersquoshowyoumakelistsClickheretoviewcodeimage

hairs=[brownblondred]

eyes=[brownbluegreen]

weights=[1234]

Youstartthelistwiththe[(leftbracket)whichldquoopensrdquothelistThenyouputeachitemyouwantinthelistseparatedbycommassimilartofunctionargumentsLastlyendthelistwitha](rightbracket)toindicatethatitrsquosoverPythonthentakesthislistandallitscontentsandassignsthemtothevariable

WarningThisiswherethingsgettrickyforpeoplewhocanrsquotcodeYourbrainhasbeentaughtthattheworldisflatRememberinthelastexercisewhereyouputif-statementsinsideif-statementsThatprobablymadeyourbrainhurtbecausemostpeopledonotponderhowtoldquonestrdquothingsinsidethingsInprogrammingnestedstructuresareallovertheplaceYouwillfindfunctionsthatcallotherfunctionsthathaveif-statementsthathavelistswithlistsinsidelistsIfyouseeastructurelikethisthatyoucanrsquotfigureouttakeoutapencilandpaperandbreakitdownmanuallybitbybituntilyouunderstandit

Wenowwillbuildsomelistsusingsomefor-loopsandprintthemoutClickheretoviewcodeimage

ex32py

1the_count=[12345]

2fruits=[applesorangespearsapricots]

3change=[1pennies2dimes3quarters]

4

5thisfirstkindoffor-loopgoesthroughalist

6fornumberinthe_count

7print(fThisiscountnumber)

8

9sameasabove

10forfruitinfruits

11print(fAfruitoftypefruit)

12

13alsowecangothroughmixedliststoo

14noticewehavetousesincewedontknowwhatsinit

15foriinchange

16print(fIgoti)

17

18wecanalsobuildlistsfirststartwithanemptyone

19elements=[]

20

21thenusetherangefunctiontodo0to5counts

22foriinrange(06)

23print(fAddingitothelist)

24appendisafunctionthatlistsunderstand

25elementsappend(i)

26

27nowwecanprintthemouttoo

28foriinelements

29print(fElementwasi)

WhatYouShouldSee

Exercise32Session

$python36ex32py

Thisiscount1

Thisiscount2

Thisiscount3

Thisiscount4

Thisiscount5

Afruitoftypeapples

Afruitoftypeoranges

Afruitoftypepears

Afruitoftypeapricots

Igot1

Igotpennies

Igot2

Igotdimes

Igot3

Igotquarters

Adding0tothelist

Adding1tothelist

Adding2tothelist

Adding3tothelist

Adding4tothelist

Adding5tothelist

Elementwas0

Elementwas1

Elementwas2

Elementwas3

Elementwas4

Elementwas5

StudyDrills1TakealookathowyouusedrangeLookuptherangefunctiontounderstandit

2Couldyouhaveavoidedthatfor-loopentirelyonline22andjustassignedrange(06)directlytoelements

3FindthePythondocumentationonlistsandreadaboutthemWhatotheroperationscanyoudotolistsbesidesappend

CommonStudentQuestionsHowdoyoumakea2-dimensional(2D)listThatrsquosalistinalistlikethis[[123][456]]

ArenrsquotlistsandarraysthesamethingThatdependsonthelanguageandtheimplementationInclassictermsalistisverydifferentfromanarraybecauseofhowtheyrsquoreimplementedInRubythoughtheycallthesearraysInPythontheycallthemlistsJustcalltheselistsfornowsincethatrsquoswhatPythoncallsthem

Whyisafor-loopabletouseavariablethatisnrsquotdefinedyetThevariableisdefinedbythefor-loopwhenitstartsinitializingittothecurrentelementoftheloopiterationeachtimethrough

Whydoesforiinrange(13)onlylooptwotimesinsteadofthreetimesTherange()functiononlydoesnumbersfromthefirsttothelastnotincludingthelastSoitstopsattwonotthreeintheprecedingThisturnsouttobethemostcommonwaytodothiskindofloop

Whatdoeselementsappend()doItsimplyappendstotheendofthelistOpenupthePythonshellandtryafewexampleswithalistyoumakeAnytimeyourunintothingslikethisalwaystrytoplaywiththeminteractivelyinthePythonshell

Exercise33WhileLoops

Nowtototallyblowyourmindwithanewloopthewhile-loopAwhile-loopwillkeepexecutingthecodeblockunderitaslongasaBooleanexpressionisTrueWaityouhavebeenkeepingupwiththeterminologyrightThatifwewritealineandenditwitha(colon)thenthattellsPythontostartanewblockofcodeThenweindentandthatrsquosthenewcodeThisisallaboutstructuringyourprogramssothatPythonknowswhatyoumeanIfyoudonotgetthatideathengobackanddosomemoreworkwithif-statementsfunctionsandthefor-loopuntilyougetitLateronwersquollhavesomeexercisesthatwilltrainyourbraintoreadthesestructuressimilartohowweburnedBooleanexpressionsintoyourbrainBacktowhile-loopsWhattheydoissimplydoatestlikeanif-statementbutinsteadofrunningthecodeblockoncetheyjumpbacktotheldquotoprdquowherethewhileisandrepeatAwhile-looprunsuntiltheexpressionisFalseHerersquostheproblemwithwhile-loopsSometimestheydonotstopThisisgreatifyourintentionistojustkeeploopinguntiltheendoftheuniverseOtherwiseyoualmostalwayswantyourloopstoendeventuallyToavoidtheseproblemstherearesomerulestofollow1Makesurethatyouusewhile-loopssparinglyUsuallyafor-loopisbetter

2ReviewyourwhilestatementsandmakesurethattheBooleantestwillbecomeFalseatsomepoint

3Whenindoubtprintoutyourtestvariableatthetopandbottomofthewhile-looptoseewhatitrsquosdoing

Inthisexerciseyoulearnthewhile-loopwhiledoingthesethreechecksClickheretoviewcodeimage

ex33py

1i=0

2numbers=[]

3

4whileilt6

5print(fAtthetopiisi)

6numbersappend(i)

7

8i=i+1

9print(Numbersnownumbers)

10print(fAtthebottomiisi)

11

12

13print(Thenumbers)

14

15fornuminnumbers

16print(num)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise33Session

$python36ex33py

Atthetopiis0

Numbersnow[0]

Atthebottomiis1

Atthetopiis1

Numbersnow[01]

Atthebottomiis2

Atthetopiis2

Numbersnow[012]

Atthebottomiis3

Atthetopiis3

Numbersnow[0123]

Atthebottomiis4

Atthetopiis4

Numbersnow[01234]

Atthebottomiis5

Atthetopiis5

Numbersnow[012345]

Atthebottomiis6

Thenumbers

0

1

2

3

4

5

StudyDrills

1Convertthiswhile-looptoafunctionthatyoucancallandreplace6inthetest(ilt6)withavariable

2Usethisfunctiontorewritethescripttotrydifferentnumbers3Addanothervariabletothefunctionargumentsthatyoucanpassinthatletsyouchangethe+1online8soyoucanchangehowmuchitincrementsby

4Rewritethescriptagaintousethisfunctiontoseewhateffectthathas5Writeittousefor-loopsandrangeDoyouneedtheincrementorinthemiddleanymoreWhathappensifyoudonotgetridofit

Ifatanytimeyouaredoingthisitgoescrazy(itprobablywill)justholddownCTRLandpressc(CTRL-c)andtheprogramwillabort

CommonStudentQuestionsWhatrsquosthedifferencebetweenafor-loopandawhile-loopAfor-loopcanonlyiterate(loop)ldquooverrdquocollectionsofthingsAwhile-loopcandoanykindofiteration(looping)youwantHoweverwhile-loopsarehardertogetrightandyounormallycangetmanythingsdonewithfor-loops

LoopsarehardHowdoIfigurethemoutThemainreasonpeopledonrsquotunderstandloopsisbecausetheycanrsquotfollowtheldquojumpingrdquothatthecodedoesWhenalooprunsitgoesthroughitsblockofcodeandattheenditjumpsbacktothetopTovisualizethisputprintstatementsallovertheloopprintingoutwhereintheloopPythonisrunningandwhatthevariablesaresettoatthosepointsWriteprintlinesbeforetheloopatthetopoftheloopinthemiddleandatthebottomStudytheoutputandtrytounderstandthejumpingthatrsquosgoingon

Exercise34AccessingElementsofLists

ListsareprettyusefulbutunlessyoucangetatthethingsinthemtheyarenrsquotallthatgoodYoucanalreadygothroughtheelementsofalistinorderbutwhatifyouwantsaythefifthelementYouneedtoknowhowtoaccesstheelementsofalistHerersquoshowyouwouldaccessthefirstelementofalistClickheretoviewcodeimage

animals=[beartigerpenguinzebra]

bear=animals[0]

Youtakealistofanimalsandthenyougetthefirst(1st)oneusing0HowdoesthatworkBecauseofthewaymathworksPythonstartsitslistsat0ratherthan1ItseemsweirdbuttherearemanyadvantagestothiseventhoughitismostlyarbitraryThebestwaytoexplainwhyisbyshowingyouthedifferencebetweenhowyouusenumbersandhowprogrammersusenumbersImagineyouarewatchingthefouranimalsinourlist([beartigerpenguinzebra])runinaraceTheycrossthefinishlineintheorderwehavetheminthislistTheracewasreallyexcitingbecausetheanimalsdidnrsquoteateachotherandsomehowmanagedtorunaraceYourfriendshowsuplateandwantstoknowwhowonDoesyourfriendsayldquoHeywhocameinzerothrdquoNohesaysldquoHeywhocameinfirstrdquoThisisbecausetheorderoftheanimalsisimportantYoucanrsquothavethesecondanimalwithoutthefirst(1st)animalandyoucanrsquothavethethirdwithoutthesecondItrsquosalsoimpossibletohavealdquozerothrdquoanimalsincezeromeansnothingHowcanyouhaveanothingwinaraceItjustdoesnrsquotmakesenseWecallthesekindsofnumbersldquoordinalrdquonumbersbecausetheyindicateanorderingofthingsProgrammershowevercanrsquotthinkthiswaybecausetheycanpickanyelementoutofalistatanypointToprogrammersthelistofanimalsismorelikeadeckofcardsIftheywantthetigertheygrabitIftheywantthezebratheycantakeittooThisneedtopullelementsoutoflistsatrandommeansthattheyneedawaytoindicateelementsconsistentlybyanaddressoranldquoindexrdquoandthebestwaytodothatistostarttheindicesat0TrustmeonthisthemathiswayeasierforthesekindsofaccessesThiskindofnumberisaldquocardinalrdquonumberandmeansyoucanpickatrandomsothereneedstobea0elementHowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourself

HowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourselfldquoIwantthethirdanimalrdquoyoutranslatethisldquoordinalrdquonumbertoaldquocardinalrdquonumberbysubtracting1Theldquothirdrdquoanimalisatindex2andisthepenguinYouhavetodothisbecauseyouhavespentyourwholelifeusingordinalnumbersandnowyouhavetothinkincardinalJustsubtract1andyoursquoregoodRememberordinal==ordered1stcardinal==cardsatrandom0LetrsquospracticethisTakethislistofanimalsandfollowtheexerciseswhereItellyoutowritedownwhatanimalyougetforthatordinalorcardinalnumberRememberifIsayldquofirstrdquoldquosecondrdquothenIrsquomusingordinalsosubtract1IfIgiveyoucardinal(likeldquoTheanimalat1rdquo)thenuseitdirectlyClickheretoviewcodeimage

animals=[bearpython36peacockkangaroowhale

platypus]

1Theanimalat12Thethird(3rd)animal3Thefirst(1st)animal4Theanimalat35Thefifth(5th)animal6Theanimalat27Thesixth(6th)animal8Theanimalat4

ForeachofthesewriteoutafullsentenceoftheformldquoThefirst(1st)animalisat0andisabearrdquoThensayitbackwardsldquoTheanimalat0isthe1stanimalandisabearrdquoUseyourPythontocheckyouranswers

StudyDrills1Withwhatyouknowofthedifferencebetweenthesetypesofnumberscanyouexplainwhytheyear2010inldquoJanuary12010rdquoreallyis2010andnot2009(Hintyoucanrsquotpickyearsatrandom)

2Writesomemorelistsandworkoutsimilarindexesuntilyoucantranslatethem

3UsePythontocheckyouranswers

Warning

ProgrammerswilltellyoutoreadthisguynamedDijkstraonthissubjectIrecommendyouavoidhiswritingsonthisunlessyouenjoybeingyelledatbysomeonewhostoppedprogrammingatthesametimeprogrammingstarted

Exercise35BranchesandFunctions

Youhavelearnedif-statementsfunctionsandlistsNowitrsquostimetobendyourmindTypethisinandseeifyoucanfigureoutwhatitrsquosdoingClickheretoviewcodeimage

ex35py

1fromsysimportexit

2

3defgold_room()

4print(ThisroomisfullofgoldHowmuchdoyoutake)

5

6choice=input(gt)

7if0inchoiceor1inchoice

8how_much=int(choice)

9else

10dead(Manlearntotypeanumber)

11

12ifhow_muchlt50

13print(Niceyourenotgreedyyouwin)

14exit(0)

15else

16dead(Yougreedybastard)

17

18

19defbear_room()

20print(Thereisabearhere)

21print(Thebearhasabunchofhoney)

22print(Thefatbearisinfrontofanotherdoor)

23print(Howareyougoingtomovethebear)

24bear_moved=False

25

26whileTrue

27choice=input(gt)

28

29ifchoice==takehoney

30dead(Thebearlooksatyouthenslapsyourface

off)

31elifchoice==tauntbearandnotbear_moved

32print(Thebearhasmovedfromthedoor)

33print(Youcangothroughitnow)

34bear_moved=True

35elifchoice==tauntbearandbear_moved

36dead(Thebeargetspissedoffandchewsyourleg

off)

37elifchoice==opendoorandbear_moved

38gold_room()

39else

40print(Igotnoideawhatthatmeans)

41

42

43defcthulhu_room()

44print(HereyouseethegreatevilCthulhu)

45print(Heitwhateverstaresatyouandyougoinsane)

46print(Doyoufleeforyourlifeoreatyourhead)

47

48choice=input(gt)

49

50iffleeinchoice

51start()

52elifheadinchoice

53dead(Wellthatwastasty)

54else

55cthulhu_room()

56

57

58defdead(why)

59print(whyGoodjob)

60exit(0)

61

62defstart()

63print(Youareinadarkroom)

64print(Thereisadoortoyourrightandleft)

65print(Whichonedoyoutake)

66

67choice=input(gt)

68

69ifchoice==left

70bear_room()

71elifchoice==right

72cthulhu_room()

73else

74dead(Youstumblearoundtheroomuntilyoustarve)

75

76

77start()

WhatYouShouldSeeHerersquosmeplayingthegameClickheretoviewcodeimage

Exercise35Session

$python36ex35py

Youareinadarkroom

Thereisadoortoyourrightandleft

Whichonedoyoutake

gtleft

Thereisabearhere

Thebearhasabunchofhoney

Thefatbearisinfrontofanotherdoor

Howareyougoingtomovethebear

gttauntbear

Thebearhasmovedfromthedoor

Youcangothroughitnow

gtopendoor

ThisroomisfullofgoldHowmuchdoyoutake

gt1000

YougreedybastardGoodjob

StudyDrills1Drawamapofthegameandhowyouflowthroughit2Fixallofyourmistakesincludingspellingmistakes3Writecommentsforthefunctionsyoudonotunderstand4AddmoretothegameWhatcanyoudotobothsimplifyandexpandit5Thegold_roomhasaweirdwayofgettingyoutotypeanumberWhatareallthebugsinthiswayofdoingitCanyoumakeitbetterthanwhatIrsquovewrittenLookathowint()worksforclues

CommonStudentQuestionsHelpHowdoesthisprogramworkWhenyougetstuckunderstandingapieceofcodesimplywriteanEnglishcommentaboveeverylineexplainingwhatthatlinedoesKeepyourcommentsshortandsimilartothecodeTheneitherdiagramhowthecodeworksorwriteaparagraphdescribingitIfyoudothatyoursquollgetit

WhydidyouwritewhileTrueThatmakesaninfiniteloopWhatdoesexit(0)doOnmanyoperatingsystemsaprogramcanabortwithexit(0)andthenumberpassedinwillindicateanerrorornotIfyoudoexit(1)thenitwillbeanerrorbutexit(0)willbeagoodexitThereasonitrsquosbackwardfromnormalBooleanlogic(with0==False)isthatyoucanusedifferentnumbersto

indicatedifferenterrorresultsYoucandoexit(100)foradifferenterrorresultthanexit(2)orexit(1)

Whyisinput()sometimeswrittenasinput(gt)Theparametertoinputisastringthatitshouldprintasapromptbeforegettingtheuserrsquosinput

Exercise36DesigningandDebugging

Nowthatyouknowif-statementsIrsquomgoingtogiveyousomerulesforfor-loopsandwhile-loopsthatwillkeepyououtoftroubleIrsquomalsogoingtogiveyousometipsondebuggingsothatyoucanfigureoutproblemswithyourprogramFinallyyouwilldesignalittlegamesimilartothelastexercisebutwithaslighttwist

Rulesforif-statements1Everyif-statementmusthaveanelse2IfthiselseshouldneverrunbecauseitdoesnrsquotmakesensethenyoumustuseadiefunctionintheelsethatprintsoutanerrormessageanddiesjustlikewedidinthelastexerciseThiswillfindmanyerrors

3Nevernestif-statementsmorethantwodeepandalwaystrytodothemonedeep

4Treatif-statementslikeparagraphswhereeachif-elif-elsegroupingislikeasetofsentencesPutblanklinesbeforeandafter

5YourBooleantestsshouldbesimpleIftheyarecomplexmovetheircalculationstovariablesearlierinyourfunctionanduseagoodnameforthevariable

IfyoufollowthesesimplerulesyouwillstartwritingbettercodethanmostprogrammersGobacktothelastexerciseandseeifIfollowedalloftheserulesIfnotfixmymistakes

WarningNeverbeaslavetotherulesinreallifeFortrainingpurposesyouneedtofollowtheserulestomakeyourmindstrongbutinreallifesometimestheserulesarejuststupidIfyouthinkaruleisstupidtrynotusingit

RulesforLoops1Useawhile-looponlytoloopforeverandthatmeansprobablyneverThisonlyappliestoPythonotherlanguagesaredifferent

2Useafor-loopforallotherkindsofloopingespeciallyifthereisa

fixedorlimitednumberofthingstoloopover

TipsforDebugging1DonotusealdquodebuggerrdquoAdebuggerislikedoingafull-bodyscanonasickpersonYoudonotgetanyspecificusefulinformationandyoufindawholelotofinformationthatdoesnrsquothelpandisjustconfusing

2Thebestwaytodebugaprogramistouseprinttoprintoutthevaluesofvariablesatpointsintheprogramtoseewheretheygowrong

3MakesurepartsofyourprogramsworkasyouworkonthemDonotwritemassivefilesofcodebeforeyoutrytorunthemCodealittlerunalittlefixalittle

HomeworkNowwriteagamesimilartotheonethatIcreatedinthelastexerciseItcanbeanykindofgameyouwantinthesameflavorSpendaweekonitmakingitasinterestingaspossibleForStudyDrillsuselistsfunctionsandmodules(rememberthosefromExercise13)asmuchaspossibleandfindasmanynewpiecesofPythonasyoucantomakethegameworkBeforeyoustartcodingyoumustdrawamapforyourgameCreatetheroomsmonstersandtrapsthattheplayermustgothroughonpaperbeforeyoucodeOnceyouhaveyourmaptrytocodeitupIfyoufindproblemswiththemapthenadjustitandmakethecodematchThebestwaytoworkonapieceofsoftwareisinsmallchunkslikethis

1OnasheetofpaperoranindexcardwritealistoftasksyouneedtocompletetofinishthesoftwareThisisyourto-dolist

2Picktheeasiestthingyoucandofromyourlist3WriteoutEnglishcommentsinyoursourcefileasaguideforhowyouwouldaccomplishthistaskinyourcode

4WritesomeofthecodeundertheEnglishcomments5Quicklyrunyourscriptsoseeifthatcodeworked6Keepworkinginacycleofwritingsomecoderunningittotestitandfixingituntilitworks

7CrossthistaskoffyourlistthenpickyournexteasiesttaskandrepeatThisprocesswillhelpyouworkonsoftwareinamethodicalandconsistentmannerAsyouworkupdateyourlistbyremovingtasksyoudonrsquotreallyneedandaddingonesyoudo

andaddingonesyoudo

Exercise37SymbolReview

ItrsquostimetoreviewthesymbolsandPythonwordsyouknowandpickupafewmoreforthenextfewlessonsIhavewrittenoutallthePythonsymbolsandkeywordsthatareimportanttoknowInthislessontakeeachkeywordandfirsttrytowriteoutwhatitdoesfrommemoryNextsearchonlineforitandseewhatitreallydoesThismaybedifficultbecausesomeofthesearedifficulttosearchforbuttryanywayIfyougetoneofthesewrongfrommemorymakeanindexcardwiththecorrectdefinitionandtrytoldquocorrectrdquoyourmemoryFinallyuseeachoftheseinasmallPythonprogramorasmanyasyoucangetdoneThegoalistofindoutwhatthesymboldoesmakesureyougotitrightcorrectitifyoudidnotthenuseittolockitin

Keywords

DataTypesFordatatypeswriteoutwhatmakesupeachoneForexamplewithstringswriteouthowyoucreateastringFornumberswriteoutafewnumbers

StringEscapeSequencesForstringescapesequencesusetheminstringstomakesuretheydowhatyouthinktheydo

OldStyleStringFormatsSamethingforstringformatsusetheminsomestringstoknowwhattheydoOlderPython2codeusestheseformattingcharacterstodowhatf-stringsdoTrythemoutasanalternative

OperatorsSomeofthesemaybeunfamiliartoyoubutlookthemupanywayFindoutwhattheydoandifyoustillcanrsquotfigureitoutsaveitforlater

SpendaboutaweekonthisbutifyoufinishfasterthatrsquosgreatThepointistotrytogetcoverageonallthesesymbolsandmakesuretheyarelockedinyourheadWhatrsquosalsoimportantistofindoutwhatyoudonotknowsoyoucanfixitlater

ReadingCodeNowfindsomePythoncodetoreadYoushouldbereadinganyPythoncodeyoucanandtryingtostealideasthatyoufindYouactuallyshouldhaveenoughknowledgetobeabletoreadbutmaybenotunderstandwhatthecodedoesWhatthislessonteachesishowtoapplythingsyouhavelearnedtounderstandotherpeoplersquoscodeFirstprintoutthecodeyouwanttounderstandYesprintitoutbecauseyoureyesandbrainaremoreusedtoreadingpaperthancomputerscreensMakesureyouprintafewpagesatatimeSecondgothroughyourprintoutandtakenotesonthefollowing

1Functionsandwhattheydo2Whereeachvariableisfirstgivenavalue3AnyvariableswiththesamenamesindifferentpartsoftheprogramThesemaybetroublelater

4Anyif-statementswithoutelseclausesAretheyright5Anywhile-loopsthatmightnotend6Anypartsofcodethatyoucanrsquotunderstandforwhateverreason

ThirdonceyouhaveallofthismarkeduptrytoexplainittoyourselfbywritingcommentsasyougoExplainthefunctionshowtheyareusedwhatvariablesareinvolvedandanythingyoucantofigurethiscodeoutLastonallofthedifficultpartstracethevaluesofeachvariablelinebylinefunctionbyfunctionInfactdoanotherprintoutandwriteinthemarginthevalueofeachvariablethatyouneedtoldquotracerdquoOnceyouhaveagoodideaofwhatthecodedoesgobacktothecomputerandreaditagaintoseeifyoufindnewthingsKeepfindingmorecodeanddoingthisuntilyoudonotneedtheprintoutsanymore

StudyDrills1Findoutwhataldquoflowchartrdquoisanddrawafew2Ifyoufinderrorsincodeyouarereadingtrytofixthemandsendtheauthoryourchanges

3AnothertechniqueforwhenyouarenotusingpaperistoputcommentswithyournotesinthecodeSometimesthesecouldbecometheactualcommentstohelpthenextperson

CommonStudentQuestionsHowwouldIsearchforthesethingsonlineSimplyputldquopython36rdquobeforeanythingyouwanttofindForexampletofindldquoyieldrdquosearchforldquopython36yieldrdquo

Exercise38DoingThingstoLists

YouhavelearnedaboutlistsWhenyoulearnedaboutwhile-loopsyouldquoappendedrdquonumberstotheendofalistandprintedthemoutTherewerealsoStudyDrillswhereyouweresupposedtofindalltheotherthingsyoucandotolistsinthePythondocumentationThatwasawhilebacksoreviewthosetopicsifyoudonotknowwhatIrsquomtalkingaboutFounditRememberitGoodWhenyoudidthisyouhadalistandyouldquocalledrdquothefunctionappendonitHoweveryoumaynotreallyunderstandwhatrsquosgoingonsoletrsquosseewhatwecandotolistsWhenyouwritemystuffappend(hello)youareactuallysettingoffachainofeventsinsidePythontocausesomethingtohappentothemystufflistHerersquoshowitworks1PythonseesyoumentionedmystuffandlooksupthatvariableItmighthavetolookbackwardtoseeifyoucreateditwith=ifitisafunctionargumentorifitrsquosaglobalvariableEitherwayithastofindmystufffirst

2Onceitfindsmystuffitreadsthe(period)operatorandstartstolookatvariablesthatareapartofmystuffSincemystuffisalistitknowsthatmystuffhasabunchoffunctions

3ItthenhitsappendandcomparesthenametoallthenamesthatmystuffsaysitownsIfappendisinthere(itis)thenPythongrabsthattouse

4NextPythonseesthe((openparenthesis)andrealizesldquoOhheythisshouldbeafunctionrdquoAtthispointitcalls(runsorexecutes)thefunctionjustlikenormalbutitcallsthefunctionwithanextraargument

5ThatextraargumentismystuffIknowweirdrightButthatrsquoshowPythonworkssoitrsquosbesttojustrememberitandassumethatrsquostheresultWhathappensattheendofallthisisafunctioncallthatlookslikeappend(mystuffhello)insteadofwhatyoureadwhichismystuffappend(hello)

ForthemostpartyoudonothavetoknowthatthisisgoingonbutithelpswhenyougeterrormessagesfromPythonlikethisClickheretoviewcodeimage

$python36

gtgtgtclassThing(object)

deftest(message)

print(message)

gtgtgta=Thing()

gtgtgtatest(hello)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

TypeErrortest()takesexactly1argument(2given)

gtgtgtWhatwasallthatWellthisismetypingintothePythonshell

andshowingyousomemagicYouhavenrsquotseenclassyetbutwersquollget

intothatlaterFornowyouseehowPythonsaidtest()takesexactly

1argument(2given)IfyouseethisitmeansthatPythonchanged

atest(hello)totest(ahello)andthatsomewheresomeonemessed

upanddidnrsquotaddtheargumentfora

ThismightbealottotakeinbutwersquoregoingtospendafewexercisesgettingthisconceptfirminyourbrainTokickthingsoffherersquosanexercisethatmixesstringsandlistsforallkindsoffunClickheretoviewcodeimage

ex38py

1ten_things=ApplesOrangesCrowsTelephoneLightSugar

2

3print(Waittherearenot10thingsinthatlistLetsfix

that)

4

5stuff=ten_thingssplit()

6more_stuff=[DayNightSongFrisbee

7CornBananaGirlBoy]

8

9whilelen(stuff)=10

10next_one=more_stuffpop()

11print(Addingnext_one)

12stuffappend(next_one)

13print(fTherearelen(stuff)itemsnow)

14

15print(Therewegostuff)

16

17print(Letsdosomethingswithstuff)

18

19print(stuff[1])

20print(stuff[-1])whoafancy

21print(stuffpop())

22print(join(stuff))whatcool

23print(join(stuff[35]))superstellar

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Waittherearenot10thingsinthatlistLetsfixthat

AddingBoy

Thereare7itemsnow

AddingGirl

Thereare8itemsnow

AddingBanana

Thereare9itemsnow

AddingCorn

Thereare10itemsnow

Therewego[ApplesOrangesCrowsTelephoneLight

SugarBoyGirlBananaCorn]

Letsdosomethingswithstuff

Oranges

Corn

Corn

ApplesOrangesCrowsTelephoneLightSugarBoyGirlBanana

TelephoneLight

WhatListsCanDoLetrsquossayyouwanttocreateacomputergamebasedonGoFishIfyoudonrsquotknowwhatGoFishistakethetimenowtogoreaduponitontheinternetTodothisyouwouldneedtohavesomewayoftakingtheconceptofaldquodeckofcardsrdquoandputtingitintoyourPythonprogramYouthenhavetowritePythoncodethatknowshowtoworkthisimaginaryversionofadeckofcardssothatapersonplayingyourgamethinksthatitrsquosrealevenifitisnrsquotWhatyouneedisaldquodeckofcardsrdquostructureandprogrammerscallthiskindofthingadatastructureWhatrsquosadatastructureIfyouthinkaboutitadatastructureisjustaformalwaytostructure(organize)somedata(facts)ItreallyisthatsimpleEventhoughsomedatastructurescangetinsanelycomplexalltheyareisjustawaytostorefactsinsideaprogramsoyoucanaccessthemindifferentwaysTheystructuredataIrsquollbegettingintothismoreinthenextexercisebutlistsareoneofthemostcommondatastructuresprogrammersuseAlistisanorderedlistofthingsyouwanttostoreandaccessrandomlyorlinearlybyanindexWhatRememberwhatIsaidthoughjustbecauseaprogrammersaidldquolistisalistrdquodoesnrsquotmeanthatitrsquosanymorecomplexthanwhatalistalreadyisintherealworldLetrsquoslookatthedeckofcardsasanexampleofalist1Youhaveabunchofcardswithvalues

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard3Youcantakecardsoffthetopthebottomorthemiddleatrandom4Ifyouwanttofindaspecificcardyouhavetograbthedeckandgothroughitoneatatime

LetrsquoslookatwhatIsaidldquoAnorderedlistrdquoYesdeckofcardsisinorderwithafirstandalast

ldquoofthingsyouwanttostorerdquoYescardsarethingsIwanttostoreldquoandaccessrandomlyrdquoYesIcangrabacardfromanywhereinthedeck

ldquoorlinearlyrdquoYesifIwanttofindaspecificcardIcanstartatthebeginningandgoinorder

ldquobyanindexrdquoAlmostsincewithadeckofcardsifItoldyoutogetthecardatindex19yoursquodhavetocountuntilyoufoundthatoneInourPythonliststhecomputercanjustjumprighttoanyindexyougiveit

ThatisallalistdoesandthisshouldgiveyouawaytofigureoutconceptsinprogrammingEveryconceptinprogrammingusuallyhassomerelationshiptotherealworldAtleasttheusefulonesdoIfyoucanfigureoutwhattheanalogintherealworldisthenyoucanusethattofigureoutwhatthedatastructureshouldbeabletodo

WhentoUseListsYouusealistwheneveryouhavesomethingthatmatchesthelistdatastructurersquosusefulfeatures

1IfyouneedtomaintainorderRememberthisislistedordernotsortedorderListsdonotsortforyou

2IfyouneedtoaccessthecontentsrandomlybyanumberRememberthisisusingcardinalnumbersstartingat0

3Ifyouneedtogothroughthecontentslinearly(firsttolast)Rememberthatrsquoswhatfor-loopsarefor

Thisiswhenyouusealist

StudyDrills1TakeeachfunctionthatiscalledandgothroughthestepsforfunctioncallstotranslatethemtowhatPythondoesForexamplemore_stuffpop()ispop(more_stuff)

2TranslatethesetwowaystoviewthefunctioncallsinEnglishForexamplemore_stuffpop()readsasldquoCallpoponmore_stuffrdquoMeanwhilepop(more_stuff)meansldquoCallpopwithargumentmore_stuffrdquoUnderstandhowtheyarereallythesamething

3Goreadaboutobject-orientedprogrammingonlineConfusedIwastooDonotworryYouwilllearnenoughtobedangerousandyoucanslowlylearnmorelater

4ReaduponwhataclassisinPythonDonotreadabouthowotherlanguagesusethewordldquoclassrdquoThatwillonlymessyouup

5DonotworryIfyoudonothaveanyideawhatIrsquomtalkingaboutProgrammersliketofeelsmartsotheyinventedobject-orientedprogrammingnameditOOPandthenuseditwaytoomuchIfyouthinkthatrsquoshardyoushouldtrytouseldquofunctionalprogrammingrdquo

6Find10examplesofthingsintherealworldthatwouldfitinalistTrywritingsomescriptstoworkwiththem

CommonStudentQuestionsDidnrsquotyousaytonotusewhile-loopsYessojustremembersometimesyoucanbreaktherulesifyouhaveagoodreasonOnlyidiotsareslavestorulesallthetime

Whydoesjoin(stuff)notworkThewaythedocumentationforjoiniswrittendoesnrsquotmakesenseItdoesnotworklikethatandisinsteadamethodyoucallontheinsertedstringtoputbetweenthelisttobejoinedRewriteitlikejoin(stuff)

Whydidyouuseawhile-loopTryrewritingitwithafor-loopandseeifthatrsquoseasier

Whatdoesstuff[35]doThatextractsaldquoslicerdquofromthestufflistthatisfromelement3toelement4meaningitdoesnotincludeelement5Itrsquossimilartohowrange(35)wouldwork

Exercise39DictionariesOhLovelyDictionaries

YouarenowgoingtolearnabouttheDictionarydatastructureinPythonADictionary(ordict)isawaytostoredatajustlikealistbutinsteadofusingonlynumberstogetthedatayoucanusealmostanythingThisletsyoutreatadictlikeitrsquosadatabaseforstoringandorganizingdataLetrsquoscomparewhatdictscandotowhatlistscandoYouseealistletsyoudothisClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtthings=[abcd]

gtgtgtprint(things[1])

b

gtgtgtthings[1]=z

gtgtgtprint(things[1])

z

gtgtgtthings

[azcd]

YoucanusenumberstoindexintoalistmeaningyoucanusenumberstofindoutwhatrsquosinlistsYoushouldknowthisaboutlistsbynowbutmakesureyouunderstandthatyoucanonlyusenumberstogetitemsoutofalistAdictletsyouuseanythingnotjustnumbersYesadictassociatesonethingtoanothernomatterwhatitisTakealookClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtstuff=nameZedage39height612+2

gtgtgtprint(stuff[name])

Zed

gtgtgtprint(stuff[age])

39

gtgtgtprint(stuff[height])

74

gtgtgtstuff[city]=SF

gtgtgtprint(stuff[city])

SF

YouwillseethatinsteadofjustnumberswersquoreusingstringstosaywhatwewantfromthestuffdictionaryWecanalsoputnewthingsintothedictionary

withstringsItdoesnrsquothavetobestringsthoughWecanalsodothisExercise39PythonSession

gtgtgtstuff[1]=Wow

gtgtgtstuff[2]=Neato

gtgtgtprint(stuff[1])

Wow

gtgtgtprint(stuff[2])

NeatoInthiscodeIusednumbersandthenyoucanseethereare

numbersandstringsaskeysinthedictwhenIprintitIcoulduse

anythingWellalmostbutjustpretendyoucanuseanythingfornow

OfcourseadictionarythatyoucanonlyputthingsinisprettystupidsoherersquoshowyoudeletethingswiththedelkeywordClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtdelstuff[city]

gtgtgtdelstuff[1]

gtgtgtdelstuff[2]

gtgtgtstuff

nameZedage39height74

ADictionaryExampleWersquollnowdoanexercisethatyoumuststudyverycarefullyIwantyoutotypethiscodeinandtrytounderstandwhatrsquosgoingonTakenoteofwhenyouputthingsinadictgetthemfromahashandalltheoperationsyouuseNoticehowthisexampleismappingstatestotheirabbreviationsandthentheabbreviationstocitiesinthestatesRemembermapping(orassociating)isthekeyconceptinadictionaryClickheretoviewcodeimage

ex39py

1createamappingofstatetoabbreviation

2states=

3OregonOR

4FloridaFL

5CaliforniaCA

6NewYorkNY

7MichiganMI

8

9

10createabasicsetofstatesandsomecitiesinthem

11cities=

12CASanFrancisco

13MIDetroit

14FLJacksonville

15

16

17addsomemorecities

18cities[NY]=NewYork

19cities[OR]=Portland

20

21printoutsomecities

22print(-10)

23print(NYStatehascities[NY])

24print(ORStatehascities[OR])

25

26printsomestates

27print(-10)

28print(Michigansabbreviationisstates[Michigan])

29print(Floridasabbreviationisstates[Florida])

30

31doitbyusingthestatethencitiesdict

32print(-10)

33print(Michiganhascities[states[Michigan]])

34print(Floridahascities[states[Florida]])

35

36printeverystateabbreviation

37print(-10)

38forstateabbrevinlist(statesitems())

39print(fstateisabbreviatedabbrev)

40

41printeverycityinstate

42print(-10)

43forabbrevcityinlist(citiesitems())

44print(fabbrevhasthecitycity)

45

46nowdobothatthesametime

47print(-10)

48forstateabbrevinlist(statesitems())

49print(fstatestateisabbreviatedabbrev)

50print(fandhascitycities[abbrev])

51

52print(-10)

53safelygetaabbreviationbystatethatmightnotbethere

54state=statesget(Texas)

55

56ifnotstate

57print(SorrynoTexas)

58

59getacitywithadefaultvalue

60city=citiesget(TXDoesNotExist)

61print(fThecityforthestateTXiscity)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise39Session

$python36ex39py

----------

NYStatehasNewYork

ORStatehasPortland

----------

MichigansabbreviationisMI

FloridasabbreviationisFL

----------

MichiganhasDetroit

FloridahasJacksonville

----------

OregonisabbreviatedOR

FloridaisabbreviatedFL

CaliforniaisabbreviatedCA

NewYorkisabbreviatedNY

MichiganisabbreviatedMI

----------

CAhasthecitySanFrancisco

MIhasthecityDetroit

FLhasthecityJacksonville

NYhasthecityNewYork

ORhasthecityPortland

----------

OregonstateisabbreviatedOR

andhascityPortland

FloridastateisabbreviatedFL

andhascityJacksonville

CaliforniastateisabbreviatedCA

andhascitySanFrancisco

NewYorkstateisabbreviatedNY

andhascityNewYork

MichiganstateisabbreviatedMI

andhascityDetroit

----------

SorrynoTexas

ThecityforthestateTXisDoesNotExist

WhatDictionariesCanDo

WhatDictionariesCanDoAdictionaryisanotherexampleofadatastructureandlikealistitisoneofthemostcommonlyuseddatastructuresinprogrammingAdictionaryisusedtomaporassociatethingsyouwanttostoretokeysyouneedtogetthemAgainprogrammersdonrsquotuseatermlikeldquodictionaryrdquoforsomethingthatdoesnrsquotworklikeanactualdictionaryfullofwordssoletrsquosusethatasourrealworldexampleLetrsquossayyouwanttofindoutwhatthewordldquohonorificabilitudinitatibusrdquomeansTodayyouwouldsimplycopy-pastethatwordintoasearchengineandthenfindouttheanswerandwecouldsayasearchengineislikeareallyhugesupercomplexversionoftheOxfordEnglishDictionary(OED)Beforesearchengineswhatyouwoulddoisthis1GotoyourlibraryandgetldquothedictionaryrdquoLetrsquossayitrsquostheOED

2YouknowldquohonorificabilitudinitatibusrdquostartswiththeletterldquoHrdquosoyoulookonthesideofthebookforthelittletabthathasldquoHrdquoonit

3Skimthepagesuntilyouareclosetowhereldquohonrdquostarts4SkimafewmorepagesuntilyoufindldquohonorificabilitudinitatibusrdquoorhitthebeginningoftheldquohprdquowordsandrealizethiswordisnrsquotintheOED

5Onceyoufindtheentryyoureadthedefinitiontofigureoutwhatitmeans

ThisprocessisnearlyexactlythewayadictworksandyouarebasicallyldquomappingrdquothewordldquohonorificabilitudinitatibusrdquotoitsdefinitionAdictinPythonisjustlikeadictionaryintherealworldsuchastheOED

StudyDrills1Dothissamekindofmappingwithcitiesandstatesregionsinyourcountryorsomeothercountry

2FindthePythondocumentationfordictionariesandtrytodoevenmorethingstothem

3FindoutwhatyoucanrsquotdowithdictionariesAbigoneisthattheydonothaveordersotryplayingwiththat

CommonStudentQuestionsWhatisthedifferencebetweenalistandadictionaryAlistisforanorderedlistofitemsAdictionary(ordict)isformatchingsomeitems(calledldquokeysrdquo)tootheritems(calledldquovaluesrdquo)

WhatwouldIuseadictionaryforWhenyouhavetotakeonevalueandldquolookuprdquoanothervalueInfactyoucouldcalldictionariesldquolookuptablesrdquo

WhatwouldIusealistforUsealistforanysequenceofthingsthatneedstobeinorderandyouonlyneedtolookthemupbyanumericindex

WhatifIneedadictionarybutIneedittobeinorderTakealookatthecollectionsOrderedDictdatastructureinPythonSearchforitonlinetofindthedocumentation

Exercise40ModulesClassesandObjects

Pythoniscalledanldquoobject-orientedprogramminglanguagerdquoThismeansthereisaconstructinPythoncalledaclassthatletsyoustructureyoursoftwareinaparticularwayUsingclassesyoucanaddconsistencytoyourprogramssothattheycanbeusedinacleanerwayAtleastthatrsquosthetheoryIamnowgoingtoteachyouthebeginningsofobject-orientedprogrammingclassesandobjectsusingwhatyoualreadyknowaboutdictionariesandmodulesMyproblemisthatobject-orientedprogramming(OOP)isjustplainweirdYouhavetostrugglewiththistrytounderstandwhatIsayheretypeinthecodeandinthenextexerciseIrsquollhammeritinHerewego

ModulesAreLikeDictionariesYouknowhowadictionaryiscreatedandusedandthatitisawaytomaponethingtoanotherThatmeansifyouhaveadictionarywithakeyldquoapplerdquoandyouwanttogetitthenyoudothisClickheretoviewcodeimage

ex40apy

1mystuff=appleIAMAPPLES

2print(mystuff[apple])

KeepthisideaofldquogetXfromYrdquoinyourheadandnowthinkaboutmodulesYoursquovemadeafewsofarandyoushouldknowtheyare1APythonfilewithsomefunctionsorvariablesinit

2Whichyoucanimport3Andaccessthefunctionsorvariablesofwiththe(dot)operator

ImagineIhaveamodulethatIdecidetonamemystuffpyandIputafunctioninitcalledappleHerersquosthemodulemystuffpyClickheretoviewcodeimage

ex40apy

1thisgoesinmystuffpy

2defapple()

3print(IAMAPPLES)OnceIhavethiscodeIcanusethe

moduleMyStuffwithimportandthenaccesstheapplefunction

ex40apy

1importmystuff

2mystuffapple()Icouldalsoputavariableinitnamed

tangerineClickheretoviewcodeimage

ex40apy

1defapple()

2print(IAMAPPLES)

3

4thisisjustavariable

5tangerine=Livingreflectionofadream

Icanaccessthatthesamewayex40apy

1importmystuff

2

3mystuffapple()

4print(mystufftangerine)Referbacktothedictionaryandyou

shouldstarttoseehowthisissimilartousingadictionarybut

thesyntaxisdifferentLetrsquoscompareClickheretoviewcodeimage

ex40apy

1mystuff[apple]getapplefromdict

2mystuffapple()getapplefromthemodule

3mystufftangerinesamethingitsjustavariableThismeans

wehaveaverycommonpatterninPython1Takeakey=valuestyle

container

2GetsomethingoutofitbythekeyrsquosnameInthecaseofthedictionarythekeyisastringandthesyntaxis[key]InthecaseofthemodulethekeyisanidentifierandthesyntaxiskeyOtherthanthattheyarenearlythesamething

ClassesAreLikeModulesYoucanthinkaboutamoduleasaspecializeddictionarythatcanstorePythoncodesoyoucanaccessitwiththeoperatorPythonalsohasanotherconstructthatservesasimilarpurposecalledaclassAclassisawaytotakeagroupingof

functionsanddataandplacetheminsideacontainersoyoucanaccessthemwiththe(dot)operatorIfIweretocreateaclassjustlikethemystuffmoduleIrsquoddosomethinglikethisClickheretoviewcodeimage

ex40apy

1classMyStuff(object)

2

3def__init__(self)

4selftangerine=Andnowathousandyearsbetween

5

6defapple(self)

7print(IAMCLASSYAPPLES)Thatlookscomplicated

comparedtomodulesandthereisdefinitelyalotgoingonby

comparisonbutyoushouldbeabletomakeouthowthisislikea

ldquomini-modulerdquowithMyStuffhavinganapple()functioninitWhatis

probablyconfusingisthe__init__()functionanduseof

selftangerineforsettingthetangerineinstancevariable

HerersquoswhyclassesareusedinsteadofmodulesYoucantakethisMyStuffclassanduseittocraftmanyofthemmillionsatatimeifyouwantandeachonewonrsquotinterferewitheachotherWhenyouimportamodulethereisonlyonefortheentireprogramunlessyoudosomemonsterhacksBeforeyoucanunderstandthisthoughyouneedtoknowwhatanldquoobjectrdquoisandhowtoworkwithMyStuffjustlikeyoudowiththemystuffpymodule

ObjectsAreLikeImportIfaclassislikealdquomini-modulerdquothentherehastobeaconceptsimilartoimportbutforclassesThatconceptiscalledldquoinstantiaterdquowhichisjustafancyobnoxiousoverlysmartwaytosayldquocreaterdquoWhenyouinstantiateaclasswhatyougetiscalledanobjectYouinstantiate(create)aclassbycallingtheclasslikeitrsquosafunctionlikethisex40apy

1thing=MyStuff()

2thingapple()

3print(thingtangerine)Thefirstlineistheldquoinstantiaterdquo

operationanditrsquosalotlikecallingafunctionHoweverPython

coordinatesasequenceofeventsforyoubehindthescenesIrsquollgo

throughthesestepsusingtheprecedingcodeforMyStuff1Python

looksforMyStuff()andseesthatitisaclassyoursquovedefined

2Pythoncraftsanemptyobjectwithallthefunctionsyoursquovespecifiedintheclassusingdef

3Pythonthenlookstoseeifyoumadealdquomagicrdquo__init__functionandifyouhaveitcallsthatfunctiontoinitializeyournewlycreatedemptyobject

4IntheMyStufffunction__init__youthengetthisextravariableselfwhichisthatemptyobjectPythonmadeforyouandyoucansetvariablesonitjustlikeyouwouldwithamoduledictionaryorotherobject

5Inthiscaseyousetselftangerinetoasonglyricandthenyoursquoveinitializedthisobject

6NowPythoncantakethisnewlymintedobjectandassignittothethingvariableforyoutoworkwith

ThatrsquosthebasicsofhowPythondoesthisldquomini-importrdquowhenyoucallaclasslikeafunctionRememberthatthisisnotgivingyoutheclassbutinsteadisusingtheclassasablueprintforbuildingacopyofthattypeofthingKeepinmindthatIrsquomgivingyouaslightlyinaccurateideaofhowtheseworksothatyoucanstarttobuildupanunderstandingofclassesbasedonwhatyouknowaboutmodulesThetruthisclassesandobjectssuddenlydivergefrommodulesatthispointIfIwerebeingtotallyhonestIrsquodsaysomethingmorelikethisbullClassesarelikeblueprintsordefinitionsforcreatingnewmini-modules

bullInstantiationishowyoumakeoneofthesemini-modulesandimportitatthesametimeldquoInstantiaterdquojustmeanstocreateanobjectfromtheclass

bullTheresultingcreatedmini-moduleiscalledanobjectandyouthenassignittoavariabletoworkwithit

Atthispointobjectsbehavedifferentlyfrommodulesandthisshouldonlyserveasawayforyoutobridgeovertounderstandingclassesandobjects

GettingThingsfromThingsInowhavethreewaystogetthingsfromthingsClickheretoviewcodeimage

ex40apy

1dictstyle

2mystuff[apples]

3

4modulestyle

5mystuffapples()

6print(mystufftangerine)

7

8classstyle

9thing=MyStuff()

10thingapples()

11print(thingtangerine)

AFirstClassExampleYoushouldstartseeingthesimilaritiesinthesethreekey=valuecontainertypesandprobablyhaveabunchofquestionsHangonwiththequestionsasthenextexercisewillhammerhomeyourldquoobject-orientedvocabularyrdquoInthisexerciseIjustwantyoutotypeinthiscodeandgetitworkingsothatyouhavesomeexperiencebeforemovingonClickheretoviewcodeimage

ex40py

1classSong(object)

2

3def__init__(selflyrics)

4selflyrics=lyrics

5

6defsing_me_a_song(self)

7forlineinselflyrics

8print(line)

9

10happy_bday=Song([Happybirthdaytoyou

11Idontwanttogetsued

12SoIllstoprightthere])

13

14bulls_on_parade=Song([Theyrallyaroundthafamily

15Withpocketsfullofshells])

16

17happy_bdaysing_me_a_song()

18

19bulls_on_paradesing_me_a_song()

WhatYouShouldSee

Exercise40Session

$python36ex40py

Happybirthdaytoyou

Idontwanttogetsued

SoIllstoprightthere

Theyrallyaroundthafamily

Withpocketsfullofshells

StudyDrills1Writesomemoresongsusingthisandmakesureyouunderstandthatyoursquorepassingalistofstringsasthelyrics

2Putthelyricsinaseparatevariablethenpassthatvariabletotheclasstouseinstead

3SeeifyoucanhackonthisandmakeitdomorethingsDonrsquotworryifyouhavenoideahowjustgiveitatryandseewhathappensBreakittrashitthrashityoucanrsquothurtit

4Searchonlineforldquoobject-orientedprogrammingrdquoandtrytooverflowyourbrainwithwhatyoureadDonrsquotworryifitmakesabsolutelynosensetoyouHalfofthatstuffmakesnosensetometoo

CommonStudentQuestionsWhydoIneedselfwhenImake__init__orotherfunctionsforclassesIfyoudonrsquothaveselfthencodelikecheese=FrankisambiguousThatcodeisnrsquotclearaboutwhetheryoumeantheinstancersquoscheeseattributeoralocalvariablenamedcheeseWithselfcheese=Frankitrsquosveryclearyoumeantheinstanceattributeselfcheese

Exercise41LearningtoSpeakObject-Oriented

InthisexerciseIrsquomgoingtoteachyouhowtospeakldquoobject-orientedrdquoWhatIrsquolldoisgiveyouasmallsetofwordswithdefinitionsyouneedtoknowThenIrsquollgiveyouasetofsentenceswithholesinthemthatyoursquollhavetounderstandFinallyIrsquomgoingtogiveyoualargesetofexercisesthatyouhavetocompletetomakethesesentencessolidinyourvocabulary

WordDrillsclassTellPythontomakeanewtypeofthingobjectTwomeaningsthemostbasictypeofthingandanyinstanceofsomething

instanceWhatyougetwhenyoutellPythontocreateaclassdefHowyoudefineafunctioninsideaclassselfInsidethefunctionsinaclassselfisavariablefortheinstanceobjectbeingaccessed

inheritanceTheconceptthatoneclasscaninherittraitsfromanotherclassmuchlikeyouandyourparents

compositionTheconceptthataclasscanbecomposedofotherclassesaspartsmuchlikehowacarhaswheels

attributeApropertyclasseshavethatarefromcompositionandareusuallyvariables

is-aAphrasetosaythatsomethinginheritsfromanotherasinaldquosalmonrdquois-ardquofishldquo

has-aAphrasetosaythatsomethingiscomposedofotherthingsorhasatraitasinldquoasalmonhas-amouthrdquo

TakesometimetomakeflashcardsforthesetermsandmemorizethemAsusualthiswonrsquotmaketoomuchsenseuntilafteryouarefinishedwiththisexercisebutyouneedtoknowthebasewordsfirst

PhraseDrillsNextIhavealistofPythoncodesnippetsontheleftandtheEnglishsentencesforthem

classX(Y)ldquoMakeaclassnamedXthatis-aYrdquo

classX(object)def__init__(selfJ)ldquoclassXhas-a__init__thattakesselfandJparametersrdquo

classX(object)defM(selfJ)ldquoclassXhas-afunctionnamedMthattakesselfandJparametersrdquo

foo=X()ldquoSetfootoaninstanceofclassXrdquofooM(J)ldquoFromfoogettheMfunctionandcallitwithparametersselfJrdquo

fooK=QldquoFromfoogettheKattributeandsetittoQrdquoIneachofthesewhereyouseeXYMJKQandfooyoucantreatthoselikeblankspotsForexampleIcanalsowritethesesentencesasfollows1ldquoMakeaclassnamedthatis-aYrdquo

2ldquoclasshas-a__init__thattakesselfandparametersrdquo3ldquoclasshas-afunctionnamedthattakesselfandparametersrdquo4ldquoSettoaninstanceofclassrdquo5ldquoFromgetthefunctionandcallitwithself=andparametersrdquo

6ldquoFromgettheattributeandsetittordquoAgainwritetheseonsomeflashcardsanddrillthemPutthePythoncodesnippetonthefrontandthesentenceonthebackYouhavetobeabletosaythesentenceexactlythesameeverytimewheneveryouseethatformNotsortofthesamebutexactlythesame

CombinedDrillsThefinalpreparationforyouistocombinethewordsdrillswiththephrasedrillsWhatIwantyoutodoforthisdrillisthis

1Takeaphrasecardanddrillit2Flipitoverandreadthesentenceandforeachwordinthesentencethatisinyourwordsdrillsgetthatcard

3Drillthosewordsforthatsentence4Keepgoinguntilyouareboredthentakeabreakanddoitagain

AReadingTestInowhavealittlePythonhackscriptthatwilldrillyouonthesewordsyouknowinaninfinitemannerThisisasimplescriptyoushouldbeabletofigureoutandtheonlythingitdoesisusealibrarycalledurllibtodownloadalist

ofwordsIhaveHerersquosthescriptwhichyoushouldenterintooop_testpytoworkwithitClickheretoviewcodeimage

ex41py

1importrandom

2fromurllibrequestimporturlopen

3importsys

4

5WORD_URL=httplearncodethehardwayorgwordstxt

6WORDS=[]

7

8PHRASES=

9class()

10Makeaclassnamedthatis-a

11class(object)ntdef__init__(self)

12classhas-a__init__thattakesselfand

params

13class(object)ntdef(self)

14classhas-afunctionthattakesselfand

params

15=()

16Settoaninstanceofclass

17()

18Fromgetthefunctioncallitwithparamsself

19=

20Fromgettheattributeandsetitto

21

22

23dotheywanttodrillphrasesfirst

24iflen(sysargv)==2andsysargv[1]==english

25PHRASE_FIRST=True

26else

27PHRASE_FIRST=False

28

29loadupthewordsfromthewebsite

30forwordinurlopen(WORD_URL)readlines()

31WORDSappend(str(wordstrip()encoding=utf-8))

32

33

34defconvert(snippetphrase)

35class_names=[wcapitalize()forwin

36randomsample(WORDSsnippetcount())]

37other_names=randomsample(WORDSsnippetcount())

38results=[]

39param_names=[]

40

41foriinrange(0snippetcount())

42param_count=randomrandint(13)

43param_namesappend(join(

44randomsample(WORDSparam_count)))

45

46forsentenceinsnippetphrase

47result=sentence[]

48

49fakeclassnames

50forwordinclass_names

51result=resultreplace(word1)

52

53fakeothernames

54forwordinother_names

55result=resultreplace(word1)

56

57fakeparameterlists

58forwordinparam_names

59result=resultreplace(word1)

60

61resultsappend(result)

62

63returnresults

64

65

66keepgoinguntiltheyhitCTRL-D

67try

68whileTrue

69snippets=list(PHRASESkeys())

70randomshuffle(snippets)

71

72forsnippetinsnippets

73phrase=PHRASES[snippet]

74questionanswer=convert(snippetphrase)

75ifPHRASE_FIRST

76questionanswer=answerquestion

77

78print(question)

79

80input(lt)

81print(fANSWERanswernn)

82exceptEOFError

83print(nBye)Runthisscriptandtrytotranslatethe

ldquoobject-orientedphrasesrdquointoEnglishtranslationsYoushouldsee

thatthePHRASESdicthasbothformsandthatyoujusthavetoenter

thecorrectone

PracticeEnglishtoCode

PracticeEnglishtoCodeNextyoushouldrunthescriptwiththeldquoenglishrdquooptionsothatyoudrilltheinverseoperation

$pythonoop_testpyenglishRememberthatthesephrasesareusing

nonsensewordsPartoflearningtoreadcodewellistostopplacing

somuchmeaningonthenamesusedforvariablesandclassesToo

oftenpeoplewillreadawordlikeldquoCorkrdquoandsuddenlygetderailed

becausethatwordwillconfusethemaboutthemeaningIntheabove

exampleldquoCorkrdquoisjustanarbitrarynamechosenforaclassDonrsquot

placeanyothermeaningonitandinsteadtreatitlikethepatterns

Irsquovegivenyou

ReadingMoreCodeYouarenowtogoonanewquesttoreadevenmorecodetoreadthephrasesyoujustlearnedinthecodeyoureadYouwilllookforallthefileswithclassesandthendothefollowing

1Foreachclassgiveitsnameandwhatotherclassesitinheritsfrom2Underthatlisteveryfunctionithasandtheparameterstheytake3Listalloftheattributesitusesonitsself4Foreachattributegivetheclassthisattributeis

ThegoalistogothroughrealcodeandstartlearningtoldquopatternmatchrdquothephrasesyoujustlearnedagainsthowtheyrsquoreusedIfyoudrillthisenoughyoushouldstarttoseethesepatternsshoutatyouinthecodewhereasbeforetheyjustseemedlikevagueblankspotsyoudidnrsquotknow

CommonStudentQuestionsWhatdoesresult=sentence[]doThatrsquosaPythonwayofcopyingalistYoursquoreusingthelistslicesyntax[]toeffectivelymakeaslicefromtheveryfirstelementtotheverylastone

ThisscriptishardtogetrunningBythispointyoushouldbeabletotypethisinandgetitworkingItdoeshaveafewlittletrickshereandtherebuttherersquosnothingcomplexaboutitJustdoallthethingsyoursquovelearnedsofartodebugscriptsTypeeachlineinconfirmthatitrsquosexactlylikemineandresearchanythingyoudonrsquotknowonline

ItrsquosstilltoohardYoucandothisTakeitveryslowcharacterbycharacterifyouhavetobuttypeitinexactlyandfigureoutwhatitdoes

Exercise42Is-AHas-AObjectsandClasses

AnimportantconceptthatyouhavetounderstandisthedifferencebetweenaclassandanobjectTheproblemisthereisnorealldquodifferencerdquobetweenaclassandanobjectTheyareactuallythesamethingatdifferentpointsintimeIwilldemonstratewithaZenkoanWhatisthedifferencebetweenafishandasalmonDidthatquestionsortofconfuseyouReallysitdownandthinkaboutitforaminuteImeanafishandasalmonaredifferentbutwaittheyarethesamethingrightAsalmonisakindoffishsoImeanitrsquosnotdifferentButatthesametimeasalmonisaparticulartypeoffishsoitrsquosactuallydifferentfromallotherfishThatrsquoswhatmakesitasalmonandnotahalibutSoasalmonandafisharethesamebutdifferentWeirdThisquestionisconfusingbecausemostpeopledonotthinkaboutrealthingsthiswaybuttheyintuitivelyunderstandthemYoudonotneedtothinkaboutthedifferencebetweenafishandasalmonbecauseyouknowhowtheyarerelatedYouknowasalmonisakindoffishandthatthereareotherkindsoffishwithouthavingtounderstandthatLetrsquostakeitonestepfurtherLetrsquossayyouhaveabucketfullofthreesalmonandbecauseyouareanicepersonyouhavedecidedtonamethemFrankJoeandMaryNowthinkaboutthisquestionWhatisthedifferencebetweenMaryandasalmonAgainthisisaweirdquestionbutitrsquosabiteasierthanthefishversussalmonquestionYouknowthatMaryisasalmonsoshersquosnotreallydifferentShersquosjustaspecificldquoinstancerdquoofasalmonJoeandFrankarealsoinstancesofsalmonWhatdoImeanwhenIsayinstanceImeantheywerecreatedfromsomeothersalmonandnowrepresentarealthingthathassalmon-likeattributesNowforthemind-bendingideaFishisaclassandSalmonisaclassandMaryisanobjectThinkaboutthatforasecondLetrsquosbreakitdownslowlyandseeifyougetitAfishisaclassmeaningitrsquosnotarealthingbutratherawordweattachtoinstancesofthingswithsimilarattributesGotfinsGotgillsLivesinwaterAlrightitrsquosprobablyafishSomeonewithaPhDthencomesalongandsaysldquoNomyyoungfriendthisfishisactuallySalmosalaraffectionatelyknownasasalmonrdquoThisprofessorhasjustclarifiedthefishfurtherandmadeanewclasscalledldquoSalmonrdquothathas

morespecificattributesLongernosereddishfleshbiglivesintheoceanorfreshwatertastyProbablyasalmonFinallyacookcomesalongandtellsthePhDldquoNoyouseethisSalmonrighthereIrsquollcallherMaryandIrsquomgoingtomakeatastyfilletoutofherwithanicesaucerdquoNowyouhavethisinstanceofasalmon(whichalsoisaninstanceofafish)namedMaryturnedintosomethingrealthatisfillingyourbellyIthasbecomeanobjectThereyouhaveitMaryisakindofsalmonthatisakindoffishmdashobjectisaclassisaclass

HowThisLooksinCodeThisisaweirdconceptbuttobeveryhonestyouonlyhavetoworryaboutitwhenyoumakenewclassesandwhenyouuseaclassIwillshowyoutwotrickstohelpyoufigureoutwhethersomethingisaclassoranobjectFirstyouneedtolearntwocatchphrasesldquois-ardquoandldquohas-ardquoYouusethephraseis-awhenyoutalkaboutobjectsandclassesbeingrelatedtoeachotherbyaclassrelationshipYouusehas-awhenyoutalkaboutobjectsandclassesthatarerelatedonlybecausetheyreferenceeachotherNowgothroughthispieceofcodeandreplaceeachcommentwithacommentthatsayswhetherthenextlinerepresentsanis-aorahas-arelationshipandwhatthatrelationshipisInthebeginningofthecodeIrsquovelaidoutafewexamplessoyoujusthavetowritetheremainingonesRememberis-aistherelationshipbetweenfishandsalmonwhilehas-aistherelationshipbetweensalmonandgillsClickheretoviewcodeimage

ex42py

1Animalis-aobject(yessortofconfusing)lookatthe

extracredit

2classAnimal(object)

3pass

4

5

6classDog(Animal)

7

8def__init__(selfname)

9

10selfname=name

11

12

13classCat(Animal)

14

15def__init__(selfname)

16

17selfname=name

18

19

20classPerson(object)

21

22def__init__(selfname)

23

24selfname=name

25

26Personhas-apetofsomekind

27selfpet=None

28

29

30classEmployee(Person)

31

32def__init__(selfnamesalary)

33hmmwhatisthisstrangemagic

34super(Employeeself)__init__(name)

35

36selfsalary=salary

37

38

39classFish(object)

40pass

41

42

43classSalmon(Fish)

44pass

45

46

47classHalibut(Fish)

48pass

49

50

51roveris-aDog

52rover=Dog(Rover)

53

54

55satan=Cat(Satan)

56

57

58mary=Person(Mary)

59

60

61marypet=satan

62

63

64frank=Employee(Frank120000)

65

66

67frankpet=rover

68

69

70flipper=Fish()

71

72

73crouse=Salmon()

74

75

76harry=Halibut()

AboutclassName(object)InPython3youdonotneedtoaddthe(object)afterthenameoftheclassbutthePythoncommunitybelievesinldquoexplicitisbetterthanimplicitrdquosoIandotherPythonexpertshavedecidedtoincludeitYoumayrunintocodethatdoesnothave(object)aftersimpleclassesandthoseclassesareperfectlyfineandwillworkwithclassesyoucreatethatdohave(object)AtthispointitissimplyextradocumentationandhasnoimpactonhowyourclassesworkInPython2therewasadifferencebetweenthetwotypesofclassesbutnowyoudonrsquothavetoworryaboutitTheonlytrickyparttousing(object)involvesthementalgymnasticsofsayingldquoclassNameisaclassoftypeobjectrdquoThatmaysoundconfusingtoyounowsinceitrsquosaclassthatrsquosanameobjectthatrsquosaclassbutdonrsquotfeelbadaboutthatJustthinkofclassName(object)assayingldquothisisabasicsimpleclassrdquoandyoursquollbefineFinallyinthefuturethestylesandtastesofPythonprogrammersmaychangeandthisexplicituseof(object)mightbeseenasasignthatyouareabadprogrammerIfthathappenssimplystopusingitortellthemldquoPythonZensaysexplicitisbetterthanimplicitrdquo

StudyDrills1ResearchwhyPythonaddedthisstrangeobjectclassandwhatthatmeans2Isitpossibletouseaclasslikeitrsquosanobject3FillouttheanimalsfishandpeopleinthisexercisewithfunctionsthatmakethemdothingsSeewhathappenswhenfunctionsareinaldquobase

classrdquolikeAnimalversusinsayDog4Findotherpeoplersquoscodeandworkoutalltheis-aandhas-arelationships5Makesomenewrelationshipsthatarelistsanddictionariessoyoucanalsohaveldquohas-manyrdquorelationships

6Doyouthinktherersquossuchthingasanldquois-manyrdquorelationshipReadaboutldquomultipleinheritancerdquothenavoiditifyoucan

CommonStudentQuestionsWhatarethesecommentsforThoseareldquofill-in-the-blankrdquocommentsthatyouaresupposedtofillinwiththerightis-aandhas-aconceptsReadthisexerciseagainandlookattheothercommentstoseewhatImean

Whatisthepointofselfpet=NoneThatmakessurethattheselfpetattributeofthatclassissettoadefaultofNone

Whatdoessuper(Employeeself)__init__(name)doThatrsquoshowyoucanrunthe__init__methodofaparentclassreliablySearchforldquopython36superrdquoandreadthevariousadviceonitbeingevilandgoodforyou

Exercise43BasicObject-OrientedAnalysisandDesign

IrsquomgoingtodescribeaprocesstousewhenyouwanttobuildsomethingusingPythonspecificallywithobject-orientedprogramming(OOP)WhatImeanbyaldquoprocessrdquoisthatIrsquollgiveyouasetofstepsthatyoudoinorderbutthatyouarenrsquotmeanttobeaslavetoandthatmightnotalwaysworkforeveryproblemTheyarejustagoodstartingpointformanyprogrammingproblemsandshouldnrsquotbeconsideredtheonlywaytosolvethesetypesofproblemsThisprocessisjustonewaytodoitthatyoucanfollowTheprocessisasfollows1Writeordrawabouttheproblem

2Extractkeyconceptsfrom1andresearchthem3Createaclasshierarchyandobjectmapfortheconcepts4Codetheclassesandatesttorunthem5Repeatandrefine

ThewaytolookatthisprocessisthatitisldquotopdownrdquomeaningitstartsfromtheveryabstractlooseideaandthenslowlyrefinesituntiltheideaissolidandsomethingyoucancodeIstartbyjustwritingabouttheproblemandtryingtothinkupanythingIcanaboutitMaybeIrsquollevendrawadiagramortwomaybeamapofsomekindorevenwritemyselfaseriesofemailsdescribingtheproblemThisgivesmeawaytoexpressthekeyconceptsintheproblemandalsoexplorewhatImightalreadyknowaboutitThenIgothroughthesenotesdrawingsanddescriptionsandIpulloutthekeyconceptsTherersquosasimpletricktodoingthisImakealistofallthenounsandverbsinmywritinganddrawingsthenwriteouthowtheyrsquorerelatedThisgivesmeagoodlistofnamesforclassesobjectsandfunctionsinthenextstepItakethislistofconceptsandthenresearchanythatIdonrsquotunderstandsoIcanrefinethemfurtherifneededOnceIhavemylistofconceptsIcreateasimpleoutlinetreeoftheconceptsandhowtheyarerelatedasclassesIcanusuallytakemylistofnounsandstartaskingldquoIsthisonelikeotherconceptnounsThatmeanstheyhaveacommonparentclasssowhatisitcalledrdquoIkeepdoingthisuntilIhaveaclasshierarchythatrsquosjustasimpletreelistoradiagramThenItaketheverbsIhaveandseeifthosearefunctionnamesforeachclassandputtheminmytree

WiththisclasshierarchyfiguredoutIsitdownandwritesomebasicskeletoncodethathasjusttheclassestheirfunctionsandnothingmoreIthenwriteatestthatrunsthiscodeandmakessuretheclassesIrsquovemademakesenseandworkrightSometimesImaywritethetestfirstandothertimesImightwritealittletestalittlecodealittletestandsoonuntilIhavethewholethingbuiltFinallyIkeepcyclingoverthisprocessrepeatingitandrefiningasIgoandmakingitasclearasIcanbeforedoingmoreimplementationIfIgetstuckatanyparticularpartbecauseofaconceptorproblemIhavenrsquotanticipatedthenIsitdownandstarttheprocessoveronjustthatparttofigureitoutmorebeforecontinuingIwillnowgothroughthisprocesswhilecomingupwithagameengineandagameforthisexercise

TheAnalysisofaSimpleGameEngineThegameIwanttomakeiscalledldquoGothonsfromPlanetPercal25rdquoanditwillbeasmallspaceadventuregameWithnothingmorethanthatconceptinmymindIcanexploretheideaandfigureouthowtomakethegamecometolife

WriteorDrawAbouttheProblemIrsquomgoingtowritealittleparagraphforthegameldquoAlienshaveinvadedaspaceshipandourherohastogothroughamazeofroomsdefeatingthemsohecanescapeintoanescapepodtotheplanetbelowThegamewillbemorelikeaZorkorAdventuretypegamewithtextoutputsandfunnywaystodieThegamewillinvolveanenginethatrunsamapfullofroomsorscenesEachroomwillprintitsowndescriptionwhentheplayerentersitandthentelltheenginewhatroomtorunnextoutofthemaprdquoAtthispointIhaveagoodideaforthegameandhowitwouldrunsonowIwanttodescribeeachsceneDeathThisiswhentheplayerdiesandshouldbesomethingfunny

CentralCorridorThisisthestartingpointandhasaGothonalreadystandingtherethattheplayershavetodefeatwithajokebeforecontinuing

LaserWeaponArmoryThisiswheretheherogetsaneutronbombtoblowuptheshipbeforegettingtotheescapepodIthasakeypadtheherohastoguessthenumberfor

TheBridgeThisisanotherbattlescenewithaGothonwheretheheroplacesthebomb

EscapePodThisiswheretheheroescapesbutonlyafterguessingtherightescapepod

AtthispointImightdrawoutamapofthesemaybewritemoredescriptionsofeachroommdashwhatevercomestomindasIexploretheproblem

ExtractKeyConceptsandResearchThemInowhaveenoughinformationtoextractsomeofthenounsandanalyzetheirclasshierarchyFirstImakealistofallthenouns

bullAlienbullPlayerbullShipbullMazebullRoombullScenebullGothonbullEscapePodbullPlanetbullMapbullEnginebullDeathbullCentralCorridorbullLaserWeaponArmorybullTheBridge

IwouldalsopossiblygothroughalltheverbsandseeifanyofthemmightbegoodfunctionnamesbutIrsquollskipthatfornowAtthispointImightalsoresearcheachoftheseconceptsandanythingIdonrsquotknowrightnowForexampleImightplayafewofthesetypesofgamesandmakesureIknowhowtheyworkImightresearchhowshipsaredesignedorhowbombsworkMaybeIrsquollresearchsometechnicalissuelikehowtostorethegamersquosstateinadatabaseAfterIrsquovedonethisresearchImightstartoveratstep1basedonnewinformationIhaveandrewritemydescriptionandextractnewconcepts

CreateaClassHierarchyandObjectMapfortheConceptsOnceIhavethatIturnitintoaclasshierarchybyaskingldquoWhatissimilartootherthingsrdquoIalsoaskldquoWhatisbasicallyjustanotherwordforanotherthingrdquo

RightawayIseethatldquoRoomrdquoandldquoScenerdquoarebasicallythesamethingdependingonhowIwanttodothingsIrsquomgoingtopickldquoScenerdquoforthisgameThenIseethatallthespecificroomslikeldquoCentralCorridorrdquoarebasicallyjustScenesIseealsothatDeathisbasicallyaScenewhichconfirmsmychoiceofldquoScenerdquooverldquoRoomrdquosinceyoucanhaveadeathscenebutadeathroomiskindofoddldquoMazerdquoandldquoMaprdquoarebasicallythesamesoIrsquomgoingtogowithldquoMaprdquosinceIuseditmoreoftenIdonrsquotwanttodoabattlesystemsoIrsquomgoingtoignoreldquoAlienrdquoandldquoPlayerrdquoandsavethatforlaterTheldquoPlanetrdquocouldalsojustbeanothersceneinsteadofsomethingspecificAfterallofthatthoughtprocessIstarttomakeaclasshierarchythatlookslikethisinmytexteditorMapEngineSceneDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodIthengothroughandfigureoutwhatactionsareneededoneachthingbasedonverbsinthedescriptionForexampleIknowfromthedescriptionIrsquomgoingtoneedawaytoldquorunrdquotheengineldquogetthenextscenerdquofromthemapgettheldquoopeningscenerdquoandldquoenterrdquoasceneIrsquolladdthoselikethisMapndashnext_scenendashopening_sceneEnginendashplayScenendashenterDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodNoticehowIjustput-enterunderScenesinceIknowthatallthescenesunderitwillinherititandhavetooverrideitlater

CodetheClassesandaTesttoRunThemOnceIhavethistreeofclassesandsomeofthefunctionsIopenupasourcefileinmyeditorandtrytowritethecodeforitUsuallyIrsquolljustcopy-pastethetreeintothesourcefileandthenedititintoclassesHerersquosasmallexampleofhow

intothesourcefileandthenedititintoclassesHerersquosasmallexampleofhowthismightlookatfirstwithasimplelittletestattheendofthefileClickheretoviewcodeimage

ex43_classespy

1classScene(object)

2

3defenter(self)

4pass

5

6

7classEngine(object)

8

9def__init__(selfscene_map)

10pass

11

12defplay(self)

13pass

14

15classDeath(Scene)

16

17defenter(self)

18pass

19

20classCentralCorridor(Scene)

21

22defenter(self)

23pass

24

25classLaserWeaponArmory(Scene)

26

27defenter(self)

28pass

29

30classTheBridge(Scene)

31

32defenter(self)

33pass

34

35classEscapePod(Scene)

36

37defenter(self)

38pass

39

40

41classMap(object)

42

43def__init__(selfstart_scene)

44pass

45

46defnext_scene(selfscene_name)

47pass

48

49defopening_scene(self)

50pass

51

52

53a_map=Map(central_corridor)

54a_game=Engine(a_map)

55a_gameplay()InthisfileyoucanseethatIsimplyreplicated

thehierarchyIwantedandthenaddedalittlebitofcodeattheend

torunitandseeifitallworksinthisbasicstructureInthe

latersectionsofthisexerciseyoursquollfillintherestofthiscode

andmakeitworktomatchthedescriptionofthegame

RepeatandRefineThelaststepinmylittleprocessisnrsquotsomuchastepasitisawhile-loopYoudonrsquoteverdothisasaone-passoperationInsteadyougobackoverthewholeprocessagainandrefineitbasedoninformationyoursquovelearnedfromlaterstepsSometimesIrsquollgettostep3andrealizethatIneedtoworkon1and2moresoIrsquollstopandgobackandworkonthoseSometimesIrsquollgetaflashofinspirationandjumptotheendtocodeupthesolutioninmyheadwhileIhaveittherebutthenIrsquollgobackanddothepreviousstepstomakesureIcoverallthepossibilitiesIhaveTheotherideainthisprocessisthatitrsquosnotjustsomethingyoudoatonesinglelevelbutsomethingthatyoucandoateverylevelwhenyourunintoaparticularproblemLetrsquossayIdonrsquotknowhowtowritetheEngineplaymethodyetIcanstopanddothiswholeprocessonjustthatonefunctiontofigureouthowtowriteit

TopDownversusBottomUpTheprocessistypicallylabeledldquotopdownrdquosinceitstartsatthemostabstractconcepts(thetop)andworksitswaydowntoactualimplementationIwantyoutousethisprocessIjustdescribedwhenanalyzingproblemsinthebookfromnowonbutyoushouldknowthattherersquosanotherwaytosolveproblemsinprogrammingthatstartswithcodeandgoesldquouprdquototheabstractconceptsThisotherwayislabeledldquobottomuprdquoHerearethegeneralstepsyoufollowtodothis

1Takeasmallpieceoftheproblemhackonsomecodeandgetittorunbarely

barely2Refinethecodeintosomethingmoreformalwithclassesandautomatedtests

3Extractthekeyconceptsyoursquoreusingandresearchthem4Writeadescriptionofwhatrsquosreallygoingon5Gobackandrefinethecodepossiblythrowingitoutandstartingover6Repeatmovingontosomeotherpieceoftheproblem

IfindthisprocessisbetteronceyoursquoremoresolidatprogrammingandarenaturallythinkingincodeaboutproblemsThisprocessisverygoodwhenyouknowsmallpiecesoftheoverallpuzzlebutmaybedonrsquothaveenoughinformationyetabouttheoverallconceptBreakingitdowninlittlepiecesandexploringwithcodethenhelpsyouslowlygrindawayattheproblemuntilyoursquovesolveditHoweverrememberthatyoursolutionwillprobablybemeanderingandweirdsothatrsquoswhymyversionofthisprocessinvolvesgoingbackandfindingresearchthencleaningthingsupbasedonwhatyoursquovelearned

TheCodeforldquoGothonsfromPlanetPercal25rdquoStopIrsquomgoingtoshowyoumyfinalsolutiontotheprecedingproblembutIdonrsquotwantyoutojustjumpinandtypethisupIwantyoutotaketheroughskeletoncodeIdidandtrytomakeitworkbasedonthedescriptionOnceyouhaveyoursolutionthenyoucancomebackandseehowIdiditIrsquomgoingtobreakthisfinalfileex43pydownintosectionsandexplaineachoneratherthandumpallthecodeatonceClickheretoviewcodeimage

ex43py

1fromsysimportexit

2fromrandomimportrandint

3fromtextwrapimportdedentThisisjustourbasicimportsfor

thegameTheonlynewthingistheimportofthededentfunction

fromthetextwrapmoduleThislittlefunctionwillhelpuswriteour

roomdescriptionsusing(triple-quote)stringsItsimplystrips

leadingwhite-spacefromthebeginningsoflinesinastringWithout

thisfunctionusingstylestringsfailsbecausetheyare

indentedonthescreenthesamelevelasinthePythoncode

Clickheretoviewcodeimage

ex43py

1classScene(object)

2

3defenter(self)

4print(Thissceneisnotyetconfigured)

5print(Subclassitandimplemententer())

6exit(1)AsyousawintheskeletoncodeIhaveabase

classforScenethatwillhavethecommonthingsthatallscenesdo

Inthissimpleprogramtheydonrsquotdomuchsothisismorea

demonstrationofwhatyouwoulddotomakeabaseclass

Clickheretoviewcodeimage

ex43py

1classEngine(object)

2

3def__init__(selfscene_map)

4selfscene_map=scene_map

5

6defplay(self)

7current_scene=selfscene_mapopening_scene()

8last_scene=selfscene_mapnext_scene(finished)

9

10whilecurrent_scene=last_scene

11next_scene_name=current_sceneenter()

12current_scene=

selfscene_mapnext_scene(next_scene_name)

13

14besuretoprintoutthelastscene

15current_sceneenter()IalsohavemyEngineclassand

youcanseehowIrsquomalreadyusingthemethodsforMapopening_scene

andMapnext_sceneBecauseIrsquovedoneabitofplanningIcanjust

assumeIrsquollwritethoseandthenusethembeforeIrsquovewrittentheMap

class

Clickheretoviewcodeimage

ex43py

1classDeath(Scene)

2

3quips=[

4YoudiedYoukindasuckatthis

5YourMomwouldbeproudifsheweresmarter

6Suchaluser

7Ihaveasmallpuppythatsbetteratthis

8YoureworsethanyourDadsjokes

9

10]

11

12defenter(self)

13print(Deathquips[randint(0len(selfquips)-1)])

14exit(1)MyfirstsceneistheoddscenenamedDeath

whichshowsyouthesimplestkindofsceneyoucanwrite

Clickheretoviewcodeimage

ex43py

1classCentralCorridor(Scene)

2

3defenter(self)

4print(dedent(

5TheGothonsofPlanetPercal25haveinvadedyour

shipand

6destroyedyourentirecrewYouarethelast

surviving

7memberandyourlastmissionistogettheneutron

destruct

8bombfromtheWeaponsArmoryputitinthebridge

and

9blowtheshipupaftergettingintoanescapepod

10

11Yourerunningdownthecentralcorridortothe

Weapons

12ArmorywhenaGothonjumpsoutredscalyskin

darkgrimy

13teethandevilclowncostumeflowingaroundhis

hate

14filledbodyHesblockingthedoortotheArmory

and

15abouttopullaweapontoblastyou

16))

17

18action=input(gt)

19

20ifaction==shoot

21print(dedent(

22Quickonthedrawyouyankoutyourblaster

andfire

23itattheGothonHisclowncostumeis

flowingand

24movingaroundhisbodywhichthrowsoffyour

aim

25Yourlaserhitshiscostumebutmisseshim

entirely

26Thiscompletelyruinshisbrandnewcostume

hismother

27boughthimwhichmakeshimflyintoan

insanerage

28andblastyourepeatedlyinthefaceuntil

youare

29deadThenheeatsyou

30))

31returndeath

32

33elifaction==dodge

34print(dedent(

35Likeaworldclassboxeryoudodgeweave

slipand

36sliderightastheGothonsblastercranksa

laser

37pastyourheadInthemiddleofyourartful

dodge

38yourfootslipsandyoubangyourheadonthe

metal

39wallandpassoutYouwakeupshortlyafter

onlyto

40dieastheGothonstompsonyourheadand

eatsyou

41))

42returndeath

43

44elifaction==tellajoke

45print(dedent(

46LuckyforyoutheymadeyoulearnGothon

insultsin

47theacademyYoutelltheoneGothonjoke

youknow

48Lbhezbgurevffbsngjurafurfvgfnebhaq

gurubhfr

49furfvgfnebhaqgurubhfrTheGothonstops

tries

50nottolaughthenbustsoutlaughingand

cantmove

51Whileheslaughingyourunupandshoothim

squarein

52theheadputtinghimdownthenjumpthrough

the

53WeaponArmorydoor

54))

55returnlaser_weapon_armory

56

57else

58print(DOESNOTCOMPUTE)

59returncentral_corridor

AfterthatIrsquovecreatedtheCentralCorridorwhichisthestartofthegameIrsquomdoingthescenesforthegamebeforetheMapbecauseIneedtoreferencethemlaterYoushouldalsoseehowIusethededentfunctiononline4TryremovingitlatertoseewhatitdoesClickheretoviewcodeimage

ex43py

1classLaserWeaponArmory(Scene)

2

3defenter(self)

4print(dedent(

5YoudoadiverollintotheWeaponArmory

crouchandscan

6theroomformoreGothonsthatmightbe

hidingItsdead

7quiettooquietYoustandupandruntothe

farsideof

8theroomandfindtheneutronbombinits

container

9Theresakeypadlockontheboxandyouneed

thecodeto

10getthebomboutIfyougetthecodewrong10

timesthen

11thelockclosesforeverandyoucantgetthe

bombThe

12codeis3digits

13))

14

15code=frandint(19)randint(19)randint(19)

16guess=input([keypad]gt)

17guesses=0

18

19whileguess=codeandguesseslt10

20print(BZZZZEDDD)

21guesses+=1

22guess=input([keypad]gt)

23

24ifguess==code

25print(dedent(

26Thecontainerclicksopenandtheseal

breaksletting

27gasoutYougrabtheneutronbombandrun

asfastas

28youcantothebridgewhereyoumustplace

itinthe

29rightspot

30))

31returnthe_bridge

32else

33print(dedent(

34Thelockbuzzesonelasttimeandthenyou

heara

35sickeningmeltingsoundasthemechanismis

fused

36togetherYoudecidetositthereand

finallythe

37Gothonsblowuptheshipfromtheirshipand

youdie

38))

39returndeath

40

41

42

43classTheBridge(Scene)

44

45defenter(self)

46print(dedent(

47YouburstontotheBridgewiththenetron

destructbomb

48underyourarmandsurprise5Gothonswhoare

tryingto

49takecontroloftheshipEachofthemhasan

evenuglier

50clowncostumethanthelastTheyhavent

pulledtheir

51weaponsoutyetastheyseetheactivebomb

underyour

52armanddontwanttosetitoff

53))

54

55action=input(gt)

56

57ifaction==throwthebomb

58print(dedent(

59Inapanicyouthrowthebombatthegroup

ofGothons

60andmakealeapforthedoorRightasyou

dropita

61Gothonshootsyourightinthebackkilling

youAs

62youdieyouseeanotherGothonfrantically

tryto

63disarmthebombYoudieknowingtheywill

probably

64blowupwhenitgoesoff

65))

66returndeath

67

68elifaction==slowlyplacethebomb

69print(dedent(

70Youpointyourblasteratthebombunder

yourarmand

71theGothonsputtheirhandsupandstartto

sweat

72Youinchbackwardtothedooropenitand

then

73carefullyplacethebombonthefloor

pointingyour

74blasteratitYouthenjumpbackthrough

thedoor

75punchtheclosebuttonandblastthelockso

the

76GothonscantgetoutNowthatthebombis

placed

77youruntotheescapepodtogetoffthis

tincan

78))

79

80returnescape_pod

81else

82print(DOESNOTCOMPUTE)

83returnthe_bridge

84

85

86classEscapePod(Scene)

87

88defenter(self)

89print(dedent(

90Yourushthroughtheshipdesperatelytryingto

makeitto

91theescapepodbeforethewholeship

explodesItseems

92likehardlyanyGothonsareontheshipsoyour

runis

93clearofinterferenceYougettothechamber

withthe

94escapepodsandnowneedtopickoneto

takeSomeof

95themcouldbedamagedbutyoudonthavetimeto

look

96Theres5podswhichonedoyoutake

97))

98

99good_pod=randint(15)

100guess=input([pod]gt)

101

102

103ifint(guess)=good_pod

104print(dedent(

105Youjumpintopodguessandhittheeject

button

106Thepodescapesoutintothevoidofspace

then

107implodesasthehullrupturescrushingyour

bodyinto

108jamjelly

109))

110returndeath

111else

112print(dedent(

113Youjumpintopodguessandhittheeject

button

114Thepodeasilyslidesoutintospaceheading

tothe

115planetbelowAsitfliestotheplanet

youlook

116backandseeyourshipimplodethenexplode

likea

117brightstartakingouttheGothonshipat

thesame

118timeYouwon

119))

120

121returnfinished

122

123classFinished(Scene)

124

125defenter(self)

126print(YouwonGoodjob)

127returnfinished

ThisistherestofthegamersquosscenesandsinceIknowIneedthemandhavethoughtabouthowtheyrsquollflowtogetherIrsquomabletocodethemupdirectlyIncidentallyIwouldnrsquotjusttypeallthiscodeinRememberIsaidtotryandbuildthisincrementallyonelittlebitatatimeIrsquomjustshowingyouthefinalresultClickheretoviewcodeimage

ex43py

1classMap(object)

2

3scenes=

4central_corridorCentralCorridor()

5laser_weapon_armoryLaserWeaponArmory()

6the_bridgeTheBridge()

7escape_podEscapePod()

8deathDeath()

9finishedFinished()

10

11

12def__init__(selfstart_scene)

13selfstart_scene=start_scene

14

15defnext_scene(selfscene_name)

16val=Mapscenesget(scene_name)

17returnval

18

19defopening_scene(self)

20returnselfnext_scene(selfstart_scene)AfterthatI

havemyMapclassandyoucanseeitisstoringeachscenebyname

inadictionaryandthenIrefertothatdictwithMapscenesThis

isalsowhythemapcomesafterthescenesbecausethedictionaryhas

torefertothescenessotheyhavetoexist

Clickheretoviewcodeimage

ex43py

1a_map=Map(central_corridor)

2a_game=Engine(a_map)

3a_gameplay()FinallyIrsquovegotmycodethatrunsthegameby

makingaMapthenhandingthatmaptoanEnginebeforecallingplay

tomakethegamework

WhatYouShouldSeeMakesureyouunderstandthegameandthatyoutriedtosolveityourselffirstOnethingtodoifyoursquorestumpedischeatalittlebyreadingmycodethencontinuetryingtosolveityourselfWhenIrunmygameitlookslikethisClickheretoviewcodeimage

Exercise43Session

$python36ex43py

TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyedyourentirecrewYouarethelastsurviving

memberandyourlastmissionistogettheneutrondestruct

bombfromtheWeaponsArmoryputitinthebridgeand

blowtheshipupaftergettingintoanescapepod

YourerunningdownthecentralcorridortotheWeapons

ArmorywhenaGothonjumpsoutredscalyskindarkgrimy

teethandevilclowncostumeflowingaroundhishate

filledbodyHesblockingthedoortotheArmoryand

abouttopullaweapontoblastyou

gtdodge

Likeaworldclassboxeryoudodgeweaveslipand

sliderightastheGothonsblastercranksalaser

pastyourheadInthemiddleofyourartfuldodge

yourfootslipsandyoubangyourheadonthemetal

wallandpassoutYouwakeupshortlyafteronlyto

dieastheGothonstompsonyourheadandeatsyou

YoureworsethanyourDadsjokes

StudyDrills1ChangeitMaybeyouhatethisgameItcouldbetooviolentormaybeyouarenrsquotintosci-fiGetthegameworkingthenchangeittowhatyoulikeThisisyourcomputeryoumakeitdowhatyouwant

2IhaveabuginthiscodeWhyisthedoorlockguessing11times3Explainhowreturningthenextroomworks4AddcheatcodestothegamesoyoucangetpastthemoredifficultroomsIcandothiswithtwowordsononeline

5GobacktomydescriptionandanalysisthentrytobuildasmallcombatsystemfortheheroandthevariousGothonsheencounters

6ThisisactuallyasmallversionofsomethingcalledaldquofinitestatemachinerdquoReadaboutthemTheymightnotmakesensebuttryanyway

CommonStudentQuestionsWherecanIfindstoriesformyowngamesYoucanmakethemupjustlikeyouwouldtellastorytoafriendOryoucantakesimplescenesfromabookormovieyoulike

Exercise44InheritanceversusComposition

InthefairytalesaboutheroesdefeatingevilvillainstherersquosalwaysadarkforestofsomekindItcouldbeacaveaforestanotherplanetjustsomeplacethateveryoneknowstheheroshouldnrsquotgoOfcourseshortlyafterthevillainisintroducedyoufindoutyestheherohastogotothatstupidforesttokillthebadguyItseemstheherojustkeepsgettingintosituationsthatrequirehimtoriskhislifeinthisevilforestYourarelyreadfairytalesabouttheheroeswhoaresmartenoughtojustavoidthewholesituationentirelyYouneverhearaherosayldquoWaitaminuteifIleavetomakemyfortunesonthehighseasleavingButtercupbehindIcoulddieandthenshersquodhavetomarrysomeuglyprincenamedHumperdinkHumperdinkIthinkIrsquollstayhereandstartaFarmBoyforRentbusinessrdquoIfhedidthattherersquodbenofireswampdyingreanimationswordfightsgiantsoranykindofstoryreallyBecauseofthistheforestinthesestoriesseemstoexistlikeablackholethatdragstheheroinnomatterwhattheydoInobject-orientedprogramminginheritanceistheevilforestExperiencedprogrammersknowtoavoidthisevilbecausetheyknowthatdeepinsidetheDarkForestInheritanceistheEvilQueenMultipleInheritanceShelikestoeatsoftwareandprogrammerswithhermassivecomplexityteethchewingonthefleshofthefallenButtheforestissopowerfulandsotemptingthatnearlyeveryprogrammerhastogointoitandtrytomakeitoutalivewiththeEvilQueenrsquosheadbeforetheycancallthemselvesrealprogrammersYoujustcanrsquotresisttheInheritanceForestrsquospullsoyougoinAftertheadventureyoulearntojuststayoutofthatstupidforestandbringanarmyifyouareeverforcedtogoinagainThisisbasicallyafunnywaytosaythatIrsquomgoingtoteachyousomethingyoushouldusecarefullycalledinheritanceProgrammerswhoarecurrentlyintheforestbattlingtheQueenwillprobablytellyouthatyouhavetogoinTheysaythisbecausetheyneedyourhelpsincewhattheyrsquovecreatedisprobablytoomuchforthemtohandleButyoushouldalwaysrememberthisMostoftheusesofinheritancecanbesimplifiedorreplacedwithcompositionandmultipleinheritanceshouldbeavoidedatallcosts

WhatIsInheritanceInheritanceisusedtoindicatethatoneclasswillgetmostorallofitsfeaturesfromaparentclassThishappensimplicitlywheneveryouwriteclass

Foo(Bar)whichsaysldquoMakeaclassFoothatinheritsfromBarrdquoWhenyoudothisthelanguagemakesanyactionthatyoudooninstancesofFooalsoworkasiftheyweredonetoaninstanceofBarDoingthisletsyouputcommonfunctionalityintheBarclassthenspecializethatfunctionalityintheFooclassasneededWhenyouaredoingthiskindofspecializationtherearethreewaysthattheparentandchildclassescaninteract1Actionsonthechildimplyanactionontheparent

2Actionsonthechildoverridetheactionontheparent3Actionsonthechildaltertheactionontheparent

Iwillnowdemonstrateeachoftheseinorderandshowyoucodeforthem

ImplicitInheritanceFirstIwillshowyoutheimplicitactionsthathappenwhenyoudefineafunctionintheparentbutnotinthechildClickheretoviewcodeimage

ex44apy

1classParent(object)

2

3defimplicit(self)

4print(PARENTimplicit())

5

6classChild(Parent)

7pass

8

9dad=Parent()

10son=Child()

11

12dadimplicit()

13sonimplicit()TheuseofpassundertheclassChildishow

youtellPythonthatyouwantanemptyblockThiscreatesaclass

namedChildbutsaysthattherersquosnothingnewtodefineinit

InsteaditwillinheritallofitsbehaviorfromParentWhenyourun

thiscodeyougetthefollowingExercise44aSession

$python36ex44apy

PARENTimplicit()

PARENTimplicit()NoticehoweventhoughIrsquomcallingsonimplicit()

online13andeventhoughChilddoesnothaveanimplicitfunction

defineditstillworksanditcallstheonedefinedinParentThis

showsyouthatifyouputfunctionsinabaseclass(ieParent)

thenallsubclasses(ieChild)willautomaticallygetthose

featuresVeryhandyforrepetitivecodeyouneedinmanyclasses

OverrideExplicitlyTheproblemwithhavingfunctionscalledimplicitlyissometimesyouwantthechildtobehavedifferentlyInthiscaseyouwanttooverridethefunctioninthechildeffectivelyreplacingthefunctionalityTodothisjustdefineafunctionwiththesamenameinChildHerersquosanexampleClickheretoviewcodeimage

ex44bpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6classChild(Parent)

7

8defoverride(self)

9print(CHILDoverride())

10

11dad=Parent()

12son=Child()

13

14dadoverride()

15sonoverride()InthisexampleIhaveafunctionnamedoverride

inbothclassessoletrsquosseewhathappenswhenIrunit

Exercise44bSession

$python36ex44bpy

PARENToverride()

CHILDoverride()Asyoucanseewhenline14runsitrunsthe

Parentoverridefunctionbecausethatvariable(dad)isaParentBut

whenline15runsitprintsouttheChildoverridemessagesbecause

sonisaninstanceofChildandChildoverridesthatfunctionby

definingitsownversion

Takeabreakrightnowandtryplayingwiththesetwoconceptsbeforecontinuing

AlterBeforeorAfter

AlterBeforeorAfterThethirdwaytouseinheritanceisaspecialcaseofoverridingwhereyouwanttoalterthebehaviorbeforeoraftertheParentclassrsquosversionrunsYoufirstoverridethefunctionjustlikeinthelastexamplebutthenyouuseaPythonbuilt-infunctionnamedsupertogettheParentversiontocallHerersquostheexampleofdoingthatsoyoucanmakesenseofthisdescriptionClickheretoviewcodeimage

ex44cpy

1classParent(object)

2

3defaltered(self)

4print(PARENTaltered())

5

6classChild(Parent)

7

8defaltered(self)

9print(CHILDBEFOREPARENTaltered())

10super(Childself)altered()

11print(CHILDAFTERPARENTaltered())

12

13dad=Parent()

14son=Child()

15

16dadaltered()

17sonaltered()Theimportantlineshereare9ndash11whereinthe

ChildIdothefollowingwhensonaltered()iscalled1Because

IrsquoveoverriddenParentalteredtheChildalteredversionrunsand

line9executeslikeyoursquodexpect

2InthiscaseIwanttodoabeforeandaftersoafterline9IwanttousesupertogettheParentalteredversion

3Online10Icallsuper(Childself)altered()whichisawareofinheritanceandwillgettheParentclassforyouYoushouldbeabletoreadthisasldquocallsuperwithargumentsChildandselfthencallthefunctionalteredonwhateveritreturnsrdquo

4AtthispointtheParentalteredversionofthefunctionrunsandthatprintsouttheParentmessage

5FinallythisreturnsfromtheParentalteredandtheChildalteredfunctioncontinuestoprintouttheaftermessage

IfyourunthisyoushouldseethisClickheretoviewcodeimage

Exercise44cSession

$python36ex44cpy

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

AllThreeCombinedTodemonstratealloftheseIhaveafinalversionthatshowseachkindofinteractionfrominheritanceinonefileClickheretoviewcodeimage

ex44dpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6defimplicit(self)

7print(PARENTimplicit())

8

9defaltered(self)

10print(PARENTaltered())

11

12classChild(Parent)

13

14defoverride(self)

15print(CHILDoverride())

16

17defaltered(self)

18print(CHILDBEFOREPARENTaltered())

19super(Childself)altered()

20print(CHILDAFTERPARENTaltered())

21

22dad=Parent()

23son=Child()

24

25dadimplicit()

26sonimplicit()

27

28dadoverride()

29sonoverride()

30

31dadaltered()

32sonaltered()Gothrougheachlineofthiscodeandwritea

commentexplainingwhatthatlinedoesandwhetheritrsquosanoverride

ornotThenrunitandconfirmyougetwhatyouexpectedClickhere

toviewcodeimage

Exercise44dSession

$python36ex44dpy

PARENTimplicit()

PARENTimplicit()

PARENToverride()

CHILDoverride()

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

TheReasonforsuper()ThisshouldseemlikecommonsensebutthenwegetintotroublewithathingcalledmultipleinheritanceMultipleinheritanceiswhenyoudefineaclassthatinheritsfromoneormoreclasseslikethisClickheretoviewcodeimage

classSuperFun(ChildBadStuff)

passThisislikesayingldquoMakeaclassnamedSuperFunthat

inheritsfromtheclassesChildandBadStuffatthesametimerdquo

InthiscasewheneveryouhaveimplicitactionsonanySuperFuninstancePythonhastolookupthepossiblefunctionintheclasshierarchyforbothChildandBadStuffbutitneedstodothisinaconsistentorderTodothisPythonusesldquomethodresolutionorderrdquo(MRO)andanalgorithmcalledC3togetitstraightBecausetheMROiscomplexandawell-definedalgorithmisusedPythoncanrsquotleaveittoyoutogettheMROrightInsteadPythongivesyouthesuper()functionwhichhandlesallofthisforyouintheplacesthatyouneedthealteringtypeofactionsasIdidinChildalteredWithsuper()youdonrsquothavetoworryaboutgettingthisrightandPythonwillfindtherightfunctionforyou

Usingsuper()with__init__Themostcommonuseofsuper()isactuallyin__init__functionsinbaseclassesThisisusuallytheonlyplacewhereyouneedtodosomethingsina

childthencompletetheinitializationintheparentHerersquosaquickexampleofdoingthatintheChildClickheretoviewcodeimage

classChild(Parent)

def__init__(selfstuff)

selfstuff=stuff

super(Childself)__init__()Thisisprettymuchthesameas

theChildalteredexampleaboveexceptIrsquomsettingsomevariablesin

the__init__beforehavingtheParentinitializewithits

Parent__init__

CompositionInheritanceisusefulbutanotherwaytodotheexactsamethingisjusttouseotherclassesandmodulesratherthanrelyonimplicitinheritanceIfyoulookatthethreewaystoexploitinheritancetwoofthethreeinvolvewritingnewcodetoreplaceoralterfunctionalityThiscaneasilybereplicatedbyjustcallingfunctionsinamoduleHerersquosanexampleofdoingthisClickheretoviewcodeimage

ex44epy

1classOther(object)

2

3defoverride(self)

4print(OTHERoverride())

5

6defimplicit(self)

7print(OTHERimplicit())

8

9defaltered(self)

10print(OTHERaltered())

11

12classChild(object)

13

14def__init__(self)

15selfother=Other()

16

17defimplicit(self)

18selfotherimplicit()

19

20defoverride(self)

21print(CHILDoverride())

22

23defaltered(self)

24print(CHILDBEFOREOTHERaltered())

25selfotheraltered()

26print(CHILDAFTEROTHERaltered())

27

28son=Child()

29

30sonimplicit()

31sonoverride()

32sonaltered()InthiscodeIrsquomnotusingthenameParentsince

thereisnotaparent-childis-arelationshipThisisahas-a

relationshipwhereChildhas-aOtherthatitusestogetitswork

doneWhenIrunthisIgetthefollowingoutputExercise44e

Session

$python36ex44epy

OTHERimplicit()

CHILDoverride()

CHILDBEFOREOTHERaltered()

OTHERaltered()

CHILDAFTEROTHERaltered()Youcanseethatmostofthecodein

ChildandOtheristhesametoaccomplishthesamethingTheonly

differenceisthatIhadtodefineaChildimplicitfunctiontodo

thatoneactionIcouldthenaskmyselfifIneedthisOthertobea

classandcouldIjustmakeitintoamodulenamedotherpy

WhentoUseInheritanceorCompositionThequestionofldquoinheritanceversuscompositionrdquocomesdowntoanattempttosolvetheproblemofreusablecodeYoudonrsquotwanttohaveduplicatedcodealloveryoursoftwaresincethatrsquosnotcleanandefficientInheritancesolvesthisproblembycreatingamechanismforyoutohaveimpliedfeaturesinbaseclassesCompositionsolvesthisbygivingyoumodulesandthecapabilitytocallfunctionsinotherclassesIfbothsolutionssolvetheproblemofreusethenwhichoneisappropriateinwhichsituationsTheanswerisincrediblysubjectivebutIrsquollgiveyoumythreeguidelinesforwhentodowhich1AvoidmultipleinheritanceatallcostsasitrsquostoocomplextobereliableIfyoursquorestuckwithitthenbepreparedtoknowtheclasshierarchyandspendtimefindingwhereeverythingiscomingfrom

2Usecompositiontopackagecodeintomodulesthatareusedinmanydifferentunrelatedplacesandsituations

3Useinheritanceonlywhenthereareclearlyrelatedreusablepiecesofcodethatfitunderasinglecommonconceptorifyouhavetobecauseofsomethingyoursquoreusing

DonotbeaslavetotheserulesThethingtorememberaboutobject-orientedprogrammingisthatitisentirelyasocialconventionprogrammershavecreatedtopackageandsharecodeBecauseitrsquosasocialconventionbutonethatrsquoscodifiedinPythonyoumaybeforcedtoavoidtheserulesbecauseofthepeopleyouworkwithInthatcasefindouthowtheyusethingsandthenjustadapttothesituation

StudyDrillsThereisonlyoneStudyDrillforthisexercisebecauseitisabigexerciseGoandreadhttpwwwpythonorgdevpepspep-0008andstarttryingtouseitinyourcodeYoursquollnoticethatsomeofitisdifferentfromwhatyoursquovebeenlearninginthisbookbutnowyoushouldbeabletounderstandtheirrecommendationsandusetheminyourowncodeTherestofthecodeinthisbookmayormaynotfollowtheseguidelinesdependingonwhetheritmakesthecodemoreconfusingIsuggestyoualsodothisascomprehensionismoreimportantthanimpressingeveryonewithyourknowledgeofesotericstylerules

CommonStudentQuestionsHowdoIgetbetteratsolvingproblemsthatIhavenrsquotseenbeforeTheonlywaytogetbetteratsolvingproblemsistosolveasmanyproblemsasyoucanbyyourselfTypicallypeoplehitadifficultproblemandthenrushouttofindananswerThisisfinewhenyouhavetogetthingsdonebutifyouhavethetimetosolveityourselfthentakethattimeStopandbangyourheadagainsttheproblemforaslongaspossibletryingeverypossiblethinguntilyousolveitorgiveupAfterthattheanswersyoufindwillbemoresatisfyingandyoursquolleventuallygetbetteratsolvingproblems

ArenrsquotobjectsjustcopiesofclassesInsomelanguages(likeJavaScript)thatistrueThesearecalledprototypelanguagesandtherearenotmanydifferencesbetweenobjectsandclassesotherthanusageInPythonhoweverclassesactastemplatesthatldquomintrdquonewobjectssimilartohowcoinsaremintedusingadie(template)

Exercise45YouMakeaGame

YouneedtostartlearningtofeedyourselfHopefullyasyouhaveworkedthroughthisbookyouhavelearnedthatalltheinformationyouneedisontheinternetYoujusthavetogosearchforitTheonlythingyouhavebeenmissingaretherightwordsandwhattolookforwhenyousearchNowyoushouldhaveasenseofitsoitrsquosabouttimeyoustruggledthroughabigprojectandtriedtogetitworkingHereareyourrequirements

1MakeadifferentgamefromtheoneImade2UsemorethanonefileanduseimporttousethemMakesureyouknowwhatthatis

3Useoneclassperroomandgivetheclassesnamesthatfittheirpurposes(likeGoldRoomKoiPondRoom)

4YourrunnerwillneedtoknowabouttheseroomssomakeaclassthatrunsthemandknowsaboutthemTherersquoreplentyofwaystodothisbutconsiderhavingeachroomreturnwhatroomisnextorsettingavariableofwhatroomisnext

OtherthanthatIleaveittoyouSpendawholeweekonthisandmakeitthebestgameyoucanUseclassesfunctionsdictslistsanythingyoucantomakeitniceThepurposeofthislessonistoteachyouhowtostructureclassesthatneedotherclassesinsideotherfilesRememberIrsquomnottellingyouexactlyhowtodothisbecauseyouhavetodothisyourselfGofigureitoutProgrammingisproblemsolvingandthatmeanstryingthingsexperimentingfailingscrappingyourworkandtryingagainWhenyougetstuckaskforhelpandshowpeopleyourcodeIftheyaremeantoyouignorethemandfocusonthepeoplewhoarenotmeanandoffertohelpKeepworkingitandcleaningituntilitrsquosgoodthenshowitsomemoreGoodluckandseeyouinaweekwithyourgame

EvaluatingYourGameInthisexerciseyouwillevaluatethegameyoujustmadeMaybeyougotpartwaythroughitandyougotstuckMaybeyougotitworkingbutjustbarelyEitherwaywersquoregoingtogothroughabunchofthingsyoushouldknownowandmakesureyoucoveredtheminyourgameWersquoregoingtostudyproperlyformattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquo

formattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquoknowledgeWhywouldIhaveyoutrytodoityourselfandthenshowyouhowtodoitrightFromnowoninthebookIrsquomgoingtotrytomakeyouself-sufficientIrsquovebeenholdingyourhandmostlythiswholetimeandIcanrsquotdothatformuchlongerIrsquomnowinsteadgoingtogiveyouthingstodohaveyoudothemonyourownandthengiveyouwaystoimprovewhatyoudidYouwillstruggleatfirstandprobablybeveryfrustratedbutstickwithitandeventuallyyouwillbuildamindforsolvingproblemsYouwillstarttofindcreativesolutionstoproblemsratherthanjustcopysolutionsoutoftextbooks

FunctionStyleAlltheotherrulesIrsquovetaughtyouabouthowtomakeanicefunctionapplyherebutaddthesethings

bullForvariousreasonsprogrammerscallfunctionsthatarepartofclassesldquomethodsrdquoItrsquosmostlymarketingbutjustbewarnedthateverytimeyousayldquofunctionrdquotheyrsquollannoyinglycorrectyouandsayldquomethodrdquoIftheygettooannoyingjustaskthemtodemonstratethemathematicalbasisthatdetermineshowaldquomethodrdquoisdifferentfromaldquofunctionrdquoandtheyrsquollshutup

bullWhenyouworkwithclassesmuchofyourtimeisspenttalkingaboutmakingtheclassldquodothingsrdquoInsteadofnamingafunctionafterwhatthefunctiondoesinsteadnameitasifitrsquosacommandyouaregivingtotheclassForexamplepopissayingldquoHeylistpopthisoffrdquoItisnrsquotcalledremove_from_end_of_listbecauseeventhoughthatrsquoswhatitdoesthatrsquosnotacommandtoalist

bullKeepyourfunctionssmallandsimpleForsomereasonwhenpeoplestartlearningaboutclassestheyforgetthis

ClassStylebullYourclassshoulduseldquocamelcaserdquoasinSuperGoldFactoryratherthanldquounderscoreformatrdquoasinsuper_gold_factory

bullTrynottodotoomuchinyour__init__functionsItmakesthemhardertouse

bullYourotherfunctionsshoulduseunderscoreformatsowritemy_awesome_hairandnotmyawesomehairorMyAwesomeHair

bullBeconsistentinhowyouorganizeyourfunctionargumentsIfyourclass

hastodealwithusersdogsandcatskeepthatorderthroughoutunlessitreallydoesnrsquotmakesenseIfyouhaveonefunctionthattakes(dogcatuser)andtheothertakes(usercatdog)itrsquollbehardtouse

bullTrynottousevariablesthatcomefromthemoduleorglobalsTheyshouldbefairlyself-contained

bullAfoolishconsistencyisthehobgoblinoflittlemindsConsistencyisgoodbutfoolishlyfollowingsomeidioticmantrabecauseeveryoneelsedoesisbadstyleThinkforyourself

bullAlwaysalwayshaveclassName(object)formatorelseyouwillbeinbigtrouble

CodeStylebullGiveyourcodeverticalspacesopeoplecanreaditYouwillfindsomeverybadprogrammerswhoareabletowritereasonablecodebutwhodonotaddanyspacesThisisbadstyleinanylanguagebecausethehumaneyeandbrainusespaceandverticalalignmenttoscanandseparatevisualelementsNothavingspaceisthesameasgivingyourcodeanawesomecamouflagepaintjob

bullIfyoucanrsquotreaditoutlouditrsquosprobablyhardtoreadIfyouarehavingaproblemmakingsomethingeasytousetryreadingitoutloudNotonlydoesthisforceyoutoslowdownandreallyreaditbutitalsohelpsyoufinddifficultpassagesandthingstochangeforreadability

bullTrytodowhatotherpeoplearedoinginPythonuntilyoufindyourownstyle

bullOnceyoufindyourownstyledonotbeajerkaboutitWorkingwithotherpeoplersquoscodeispartofbeingaprogrammerandotherpeoplehavereallybadtasteTrustmeyouwillprobablyhavereallybadtastetooandnotevenrealizeit

bullIfyoufindsomeonewhowritescodeinastyleyouliketrywritingsomethingthatmimicsthatstyle

GoodCommentsbullProgrammerswilltellyouthatyourcodeshouldbereadableenoughthatyoudonotneedcommentsTheyrsquollthentellyouintheirmostofficialsoundingvoiceldquoErgooneshouldneverwritecommentsordocumentationQEDrdquoThoseprogrammersareeitherconsultantswhogetpaidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendto

paidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendtoneverworkwithotherpeopleIgnorethemandwritecomments

bullWhenyouwritecommentsdescribewhyyouaredoingwhatyouaredoingThecodealreadysayshowsowhyyoudidthingsthewayyoudidismoreimportant

bullWhenyouwritedoccommentsforyourfunctionsmakethecommentsdocumentationforsomeonewhowillhavetouseyourcodeYoudonothavetogocrazybutanicelittlesentenceaboutwhatsomeonecandowiththatfunctionhelpsalot

bullWhilecommentsaregoodtoomanyarebadandyouhavetomaintainthemKeepyourcommentsrelativelyshortandtothepointandifyouchangeafunctionreviewthecommenttomakesureitrsquosstillcorrect

EvaluateYourGameIwantyoutonowpretendyouaremeAdoptaverysternlookprintoutyourcodeandtakearedpenandmarkeverymistakeyoufindincludinganythingfromthisexerciseandfromotherguidelinesyoursquovereadsofarOnceyouaredonemarkingyourcodeupIwantyoutofixeverythingyoucameupwithThenrepeatthisacoupleoftimeslookingforanythingthatcouldbebetterUseallthetricksIrsquovegivenyoutobreakyourcodedownintothesmallesttiniestlittleanalysisyoucanThepurposeofthisexerciseistotrainyourattentiontodetailonclassesOnceyouaredonewiththisbitofcodefindsomeoneelsersquoscodeanddothesamethingGothroughaprintedcopyofsomepartofitandpointoutallthemistakesandstyleerrorsyoufindThenfixitandseeifyourfixescanbedonewithoutbreakingthatprogramIwantyoutodonothingbutevaluateandfixcodefortheweekmdashyourowncodeandotherpeoplersquosItrsquollbeprettyhardworkbutwhenyouaredoneyourbrainwillbewiredtightlikeaboxerrsquoshands

Exercise46AProjectSkeleton

ThiswillbewhereyoustartlearninghowtosetupagoodprojectldquoskeletonrdquodirectoryThisskeletondirectorywillhaveallthebasicsyouneedtogetanewprojectupandrunningItwillhaveyourprojectlayoutautomatedtestsmodulesandinstallscriptsWhenyougotomakeanewprojectjustcopythisdirectorytoanewnameandeditthefilestogetstarted

macOSLinuxSetupBeforeyoucanbeginthisexerciseyouneedtoinstallsomesoftwareforPythonbyusingatoolcalledpip36(orjustpip)toinstallnewmodulesThepip36commandshouldbeincludedwithyourpython36installationYoursquollwanttoverifythisusingthiscommand

$pip36list

pip(901)

setuptools(2880)

$

YoucanignoreanydeprecationwarningifyouseeitYoumayalsoseeothertoolsinstalledbutthebaseshouldbepipandsetuptoolsOnceyoursquoveverifiedthisyoucantheninstallvirtualenvClickheretoviewcodeimage

$sudopip36installvirtualenv

Password

Collectingvirtualenv

Downloadingvirtualenvndash1510ndashpy2py3ndashnonendashanywhl(18MB)

100|||||||||||||||||||||||||||||||||18MB11MBs

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

$

ThisisforLinuxormacOSsystemsIfyoursquoreonLinuxmacOSyoursquollwanttorunthefollowingcommandtomakesureyouusethecorrectvirtualenvClickheretoviewcodeimage

$whereisvirtualenv

LibraryFrameworksPythonframeworkVersions36binvirtualenv

YoushouldseesomethingliketheaboveonmacOSbutLinuxwillbevariableOnLinuxyoumighthaveanactualvirtualenv36commandoryoumay

bebetteroffinstallingapackageforitfromyourpackagemanagementsystemOnceyoursquoveinstalledvirtualenvyoucanuseittocreatealdquofakerdquoPythoninstallationwhichmakesiteasiertomanageversionsofyourpackagesfordifferentprojectsFirstrunthiscommandandIrsquollexplainwhatitrsquosdoingClickheretoviewcodeimage

$mkdir~venvs

$virtualenvndashndashsystemndashsitendashpackages~venvslpthw

$~venvslpthwbinactivate

(lpthw)$

Herersquoswhatrsquosgoingonlinebyline1YoucreateadirectorycalledvenvsinyourHOME~tostoreallyourvirtualenvironments

2Yourunvirtualenvandtellittoincludethesystemsitepackages(--system-site-packages)theninstructittobuildthevirtualenvin~venvslpthw

3Youthenldquosourcerdquothelpthwvirtualenvironmentbyusingtheoperatorinbashfollowedbythe~venvslpthwbinactivatescript

4Finallyyourpromptchangestoinclude(lpthw)soyouknowthatyoursquoreusingthatvirtualenvironment

NowyoucanseewherethingsareinstalledClickheretoviewcodeimage

(lpthw)$whichpython

Userszedshawvenvslpthwbinpython

(lpthw)$python

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

(lpthw)$

YoucanseethatthepythonthatgetsrunisinstalledintheUserszedshawvenvslpthwbinpythondirectoryinsteadoftheoriginallocationThisalsosolvestheproblemofhavingtotypepython36sinceitinstallsbothClickheretoviewcodeimage

$whichpython36

Userszedshawvenvslpthwbinpython36

(lpthw)$

YoursquollfindthesamethingforvirtualenvandpipcommandsThefinalstepinthissetupistoinstallnoseatestingframeworkwersquolluseinthisexerciseClickheretoviewcodeimage

$pipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB32MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)$

Windows10SetupTheWindows10installisalittlesimplerthanonLinuxormacOSbutonlyifyouhaveoneversionofPythoninstalledIfyouhavebothPython36andPython27installedthenyouareonyourownasitismuchtoodifficulttomanagemultipleinstallationsIfyouhavefollowedthebooksofarandhaveonlyPython36thenherersquoswhatyoudoFirstchangetoyourhomedirectoryandconfirmyoursquorerunningtherightversionofpythonClickheretoviewcodeimage

gtcd~

gtpython

Python360(v36041df79263a11Dec232016080612)

[MSCv190064bit(AMD64)]onwin32

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

Thenyoursquollwanttorunpiptoconfirmyouhaveabasicinstall

gtpiplist

pip(901)

setuptools(2880)

YoucansafelyignoreanydeprecationwarninganditrsquosalrightifyouhaveotherpackagesinstalledNextyoursquollinstallvirtualenvforsettingupsimplevirtualenvironmentsfortherestofthebookClickheretoviewcodeimage

gtpipinstallvirtualenv

Collectingvirtualenv

Usingcachedvirtualenvndash1510ndashpy2py3ndashnonendashanywhl

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

OnceyouhavevirtualenvinstalledyoursquollneedtomakeavenvsdirectoryandfillitwithavirtualenvironmentClickheretoviewcodeimage

gtmkdirvenvs

gtvirtualenvndashndashsystemndashsitendashpackagesvenvslpthw

Usingbaseprefix

cuserszedshappdatalocalprogramspythonpython36

Newpythonexecutablein

CUserszedshawvenvslpthwScriptspythonexe

Installingsetuptoolspipwheeldone

ThosetwocommandscreateavenvsfolderforstoringdifferentvirtualenvironmentsandthencreateyourfirstonenamedlpthwAvirtualenvironment(virtualenv)isaldquofakerdquoplacetoinstallsoftwaresothatyoucanhavedifferentversionsofdifferentpackagesforeachprojectyoursquoreworkingonOnceyouhavethevirtualenvsetupyouneedtoactivateitClickheretoviewcodeimage

gtvenvslpthwScriptsactivate

ThatwillruntheactivatescriptforPowerShellwhichconfiguresthelpthwvirtualenvforyourcurrentshellEverytimeyouwanttouseyoursoftwareforthebookyoursquollrunthiscommandYoursquollnoticeinournextcommandthatthereisnowa(lpthw)addedtothePowerShellpromptshowingyouwhichvirtualenvyoursquoreusingFinallyyoujustneedtoinstallnoseforrunningtestslaterClickheretoviewcodeimage

(lpthw)gtpipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB12MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)gt

YoursquollseethatthisinstallsnoseexceptpipwillinstallitintoyourvenvslpthwvirtualenvironmentinsteadofthemainsystempackagesdirectoryThisletsyouinstallconflictingversionsofPythonpackagesforeachprojectyouworkonwithoutinfectingyourmainsystemconfiguration

CreatingtheSkeletonProjectDirectoryFirstcreatethestructureofyourskeletondirectorywiththesecommands

$mkdirprojects

$cdprojects

$mkdirskeleton

$cdskeleton

$mkdirbinNAMEtestsdocs

IuseadirectorynamedprojectstostoreallthevariousthingsIrsquomworkingonInsidethatdirectoryIhavemyskeletondirectorythatIputthebasisofmyprojectsintoThedirectoryNAMEwillberenamedtowhateveryouarecallingyourprojectrsquosmainmodulewhenyouusetheskeletonNextweneedtosetupsomeinitialfilesHerersquoshowyoudothatonLinuxmacOS

$touchNAME__init__py

$touchtests__init__py

HerersquosthesamethingonWindowsPowerShellClickheretoviewcodeimage

$newndashitemndashtypefileNAME__init__py

$newndashitemndashtypefiletests__init__py

ThatcreatesanemptyPythonmoduledirectorywecanputourcodeinThenweneedtocreateasetuppyfilewecanusetoinstallourprojectlaterifwewantClickheretoviewcodeimage

setuppy

1try

2fromsetuptoolsimportsetup

3exceptImportError

4fromdistutilscoreimportsetup

5

6config=

7descriptionMyProject

8authorMyName

9urlURLtogetitat

10download_urlWheretodownloadit

11author_emailMyemail

12version01

13install_requires[nose]

14packages[NAME]

15scripts[]

16nameprojectname

17

18

19setup(config)

EditthisfilesothatithasyourcontactinformationandisreadytogoforwhenyoucopyitFinallyyouwillwantasimpleskeletonfilefortestsnamedtestsNAME_testspyClickheretoviewcodeimage

NAME_testspy

1fromnosetoolsimport

2importNAME

3

4defsetup()

5print(SETUP)

6

7defteardown()

8print(TEARDOWN)

9

10deftest_basic()

11print(IRAN)

FinalDirectoryStructureWhenyouaredonesettingallofthisupyourdirectoryshouldlooklikeminehere

skeleton

NAME

__init__py

bin

docs

setuppy

tests

NAME_testspy

__init__py

AndfromnowonyoushouldrunyourcommandsfromthisdirectoryIfyoucanrsquotdols-RandifyoudonrsquotseethissamestructurethenyouareinthewrongplaceForexamplepeoplecommonlygointothetestsdirectoryto

trytorunfilestherewhichwonrsquotworkTorunyourapplicationrsquostestsyouwouldneedtobeabovetestsandthislocationIhaveaboveSoifyoutrythisClickheretoviewcodeimage

$cdtestsWRONGWRONGWRONG

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran0testsin0000s

OK

ThatiswrongYouhavetobeabovetestssoassumingyoumadethismistakeyouwouldfixitbydoingthisClickheretoviewcodeimage

$cdgetoutoftests

$lsCORRECTyouarenowintherightspot

NAMEbindocssetuppytests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0004s

OK

Rememberthisbecausepeoplemakethismistakequitefrequently

WarningAtthetimeofpublicationIlearnedthatthenoseprojecthasbeenabandonedandmightnotworkwellIfyouhavestrangesyntaxerrorswhenyourunnoseteststhenlookattheerroroutputIfitreferencesldquopython27rdquointheoutputthenchancesarenosetestsistryingtorunthe27versionofPythononyourcomputerThesolutionistorunnoseusingpython36-mnoseonLinuxormacOSOnWindowsyoumaynothavethisproblembutusingpython-mnosewillsolveitifyoudo

TestingYourSetupAfteryougetallthatinstalledyoushouldbeabletodothis

$nosetests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0007s

OK

IrsquollexplainwhatthisnoseteststhingisdoinginthenextexercisebutfornowifyoudonotseethatyouprobablygotsomethingwrongMakesureyouput__init__pyfilesinyourNAMEandtestsdirectoriesandmakesureyougottestsNAME_testspyright

UsingtheSkeletonYouarenowdonewithmostofyouryakshavingWheneveryouwanttostartanewprojectjustdothis

1MakeacopyofyourskeletondirectoryNameitafteryournewproject2Rename(move)theNAMEdirectorytobethenameofyourprojectorwhateveryouwanttocallyourrootmodule

3Edityoursetuppytohavealltheinformationforyourproject4RenametestsNAME_testspytoalsohaveyourmodulename5Doublecheckitrsquosallworkingbyusingnosetestsagain6Startcoding

RequiredQuizThisexercisedoesnrsquothaveStudyDrillsinsteadherersquosquizyoushouldcomplete

1Readabouthowtouseallofthethingsyouinstalled2ReadaboutthesetuppyfileandallithastoofferWarningItisnotaverywell-writtenpieceofsoftwaresoitwillbeverystrangetouse

3Makeaprojectandstartputtingcodeintothemodulethengetthemoduleworking

4PutascriptinthebindirectorythatyoucanrunReadabouthowyoucanmakeaPythonscriptthatrsquosrunnableforyoursystem

5Mentionthebinscriptyoucreatedinyoursetuppysothatitgetsinstalled

6Useyoursetuppytoinstallyourownmoduleandmakesureitworksthenusepiptouninstallit

CommonStudentQuestions

CommonStudentQuestionsDotheseinstructionsworkonWindowsTheyshouldbutdependingontheversionofWindowsyoumayneedtostrugglewiththesetupabittogetitworkingJustkeepresearchingandtryingituntilyougetitorseeifyoucanaskamoreexperiencedPython+Windowsfriendtohelpout

WhatdoIputintheconfigdictionaryinmysetuppyMakesureyoureadthedocumentationfordistutilsathttpdocspythonorgdistutilssetupscripthtml

IcanrsquotseemtoloadtheNAMEmoduleandjustgetanImportErrorMakesurethatyoumadetheNAME__init__pyfileIfyoursquoreonWindowsmakesureyoudidnrsquotaccidentallynameitNAME__init__pytxtwhichhappensbydefaultwithsomeeditors

WhydoweneedabinfolderatallThisisjustastandardplacetoputscriptsthatarerunonthecommandlinenotaplacetoputmodules

MynosetestsrunonlyshowsonetestbeingrunIsthatrightYesthatrsquoswhatmyoutputshowstoo

Exercise47AutomatedTesting

HavingtotypecommandsintoyourgameoverandovertomakesureitrsquosworkingisannoyingWouldnrsquotitbebettertowritelittlepiecesofcodethattestyourcodeThenwhenyoumakeachangeoraddanewthingtoyourprogramyoujustldquorunyourtestsrdquoandthetestsmakesurethingsarestillworkingTheseautomatedtestswonrsquotcatchallyourbugsbuttheywillcutdownonthetimeyouspendrepeatedlytypingandrunningyourcodeEveryexerciseafterthisonewillnothaveaWhatYouShouldSeesectionbutinsteadwillhaveaWhatYouShouldTestsectionYouwillbewritingautomatedtestsforallofyourcodestartingnowandthiswillhopefullymakeyouanevenbetterprogrammerIwonrsquottrytoexplainwhyyoushouldwriteautomatedtestsIwillonlysaythatyouaretryingtobeaprogrammerandprogrammersautomateboringandtedioustasksTestingapieceofsoftwareisdefinitelyboringandtedioussoyoumightaswellwritealittlebitofcodetodoitforyouThatshouldbealltheexplanationyouneedbecauseyourreasonforwritingunittestsistomakeyourbrainstrongerYouhavegonethroughthisbookwritingcodetodothingsNowyouaregoingtotakethenextleapandwritecodethatknowsaboutothercodeyouhavewrittenThisprocessofwritingatestthatrunssomecodeyouhavewrittenforcesyoutounderstandclearlywhatyouhavejustwrittenItsolidifiesinyourbrainexactlywhatitdoesandwhyitworksandgivesyouanewlevelofattentiontodetail

WritingaTestCaseWersquoregoingtotakeaverysimplepieceofcodeandwriteonesimpletestWersquoregoingtobasethislittletestonanewprojectfromyourprojectskeletonFirstmakeanex47projectfromyourprojectskeletonHerearethestepsyoushouldtakeIrsquomgoingtogivetheseinstructionsinEnglishratherthanshowyouhowtotypethemsothatyouhavetofigureitout

1Copyskeletontoex472RenameeverythingwithNAMEtoex473ChangethewordNAMEinallthefilestoex474Finallyremoveallthepycfilestomakesureyoursquoreclean

ReferbacktoExercise46ifyougetstuckandifyoucanrsquotdothiseasilythen

maybepracticeitafewtimes

WarningRememberthatyourunthecommandnoseteststorunthetestsYoucanrunthemwithpython36ex47_testspybutitwonrsquotworkaseasilyandyoursquollhavetodoitforeachtestfile

Nextcreateasimplefileex47gamepywhereyoucanputthecodetotestThiswillbeaverysillylittleclassthatwewanttotestwiththiscodeinitClickheretoviewcodeimage

gamepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name

5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)Onceyouhavethatfile

changetheunittestskeletontothisClickheretoviewcodeimage

ex47_testspy

1fromnosetoolsimport

2fromex47gameimportRoom

3

4

5deftest_room()

6gold=Room(GoldRoom

7Thisroomhasgoldinityoucangrab

Theresa

8doortothenorth)

9assert_equal(goldnameGoldRoom)

10assert_equal(goldpaths)

11

12deftest_room_paths()

13center=Room(CenterTestroominthecenter)

14north=Room(NorthTestroominthenorth)

15south=Room(SouthTestroominthesouth)

16

17centeradd_paths(northnorthsouthsouth)

18assert_equal(centergo(north)north)

19assert_equal(centergo(south)south)

20

21deftest_map()

22start=Room(StartYoucangowestanddownahole)

23west=Room(TreesTherearetreeshereyoucango

east)

24down=Room(DungeonItsdarkdownhereyoucango

up)

25

26startadd_paths(westwestdowndown)

27westadd_paths(eaststart)

28downadd_paths(upstart)

29

30assert_equal(startgo(west)west)

31assert_equal(startgo(west)go(east)start)

32assert_equal(startgo(down)go(up)start)Thisfile

importstheRoomclassyoumadeintheex47gamemodulesothatyou

candotestsonitThereisthenasetofteststhatarefunctions

startingwithtest_Insideeachtestcasetherersquosabitofcodethat

makesaroomorasetofroomsandthenmakessuretheroomswork

thewayyouexpectthemtoworkIttestsoutthebasicroom

featuresthenthepathsthentriesoutawholemap

Theimportantfunctionshereareassert_equalwhichmakessurethatvariablesyouhavesetorpathsyouhavebuiltinaRoomareactuallywhatyouthinktheyareIfyougetthewrongresultthennosetestswillprintoutanerrormessagesoyoucangofigureitout

TestingGuidelinesFollowthisloosesetofguidelineswhenmakingyourtests

1TestfilesgointestsandarenamedBLAH_testspyotherwisenosetestswonrsquotrunthemThisalsokeepsyourtestsfromclashingwithyourothercode

2Writeonetestfileforeachmoduleyoumake3Keepyourtestcases(functions)shortbutdonotworryiftheyareabitmessyTestcasesareusuallykindofmessy

4EventhoughtestcasesaremessytrytokeepthemcleanandremoveanyrepetitivecodeyoucanCreatehelperfunctionsthatgetridofduplicatecodeYouwillthankmelaterwhenyoumakeachangeandthenhaveto

codeYouwillthankmelaterwhenyoumakeachangeandthenhavetochangeyourtestsDuplicatedcodewillmakechangingyourtestsmoredifficult

5FinallydonotgettooattachedtoyourtestsSometimesthebestwaytoredesignsomethingistojustdeleteitandstartover

WhatYouShouldSeeClickheretoviewcodeimage

Exercise47Session

$nosetests

---------------------------------------------------------------------

-

Ran3testsin0008s

OK

ThatrsquoswhatyoushouldseeifeverythingisworkingrightTrycausinganerrortoseewhatthatlookslikeandthenfixit

StudyDrills1Goreadaboutnosetestsmoreandalsoreadaboutalternatives2LearnaboutPythonrsquosldquodoctestsrdquoandseeifyoulikethembetter3Makeyourroommoreadvancedandthenuseittorebuildyourgameyetagainbutthistimeunittestasyougo

CommonStudentQuestionsIgetasyntaxerrorwhenIrunnosetestsIfyougetthatthenlookatwhattheerrorsaysandfixthatlineofcodeortheonesaboveitToolslikenosetestsarerunningyourcodeandthetestcodesotheywillfindsyntaxerrorsthesameasrunningPythonwill

Icanrsquotimportex47gameMakesureyoucreatetheex47__init__pyfileRefertoExercise46againtoseehowitrsquosdoneIfthatrsquosnottheproblemthendothisonmacOSLinuxexportPYTHONPATH=AndonWindowsClickheretoviewcodeimage

$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

FinallymakesureyoursquorerunningthetestswithnosetestsnotwithjustPython

IgetUserWarningwhenIrunnosetestsYouprobablyhavetwoversionsofPythoninstalledoryouarenrsquotusingdistributeGobackandinstalldistributeorpipasIdescribeinExercise46

Exercise48AdvancedUserInput

InpastgamesyouhandledtheuserrsquosinputbysimplyexpectingsetstringsIftheusertypedldquorunrdquoandexactlyldquorunrdquothenthegameworkedIftheytypedinsimilarphraseslikeldquorunfastrdquoitwouldfailWhatweneedisadevicethatletsuserstypephrasesinvariouswaysandthenconvertthatintosomethingthecomputerunderstandsForexamplewersquodliketohaveallofthesephrasesworkthesamebullopendoorbullopenthedoorbullgoTHROUGHthedoorbullpunchbearbullPunchTheBearintheFACEItshouldbealrightforausertowritesomethingalotlikeEnglishforyourgameandhaveyourgamefigureoutwhatitmeansTodothiswersquoregoingtowriteamodulethatdoesjustthatThismodulewillhaveafewclassesthatworktogethertohandleuserinputandconvertitintosomethingyourgamecanworkwithreliablyAsimplifiedversionoftheEnglishlanguagecouldincludethefollowingelementsbullWordsseparatedbyspacesbullSentencescomposedofthewordsbullGrammarthatstructuresthesentencesintomeaningThatmeansthebestplacetostartisfiguringouthowtogetwordsfromtheuserandwhatkindsofwordsthoseare

OurGameLexiconInourgamewehavetocreatealistofallowablewordscalledaldquolexiconrdquo

bullDirectionwordsnorthsoutheastwestdownupleftrightbackbullVerbsgostopkilleatbullStopwordstheinoffromatitbullNounsdoorbearprincesscabinetbullNumbersanystringof0through9charactersWhenwegettonounswehaveaslightproblemsinceeachroomcouldhaveadifferentsetofnounsbutletrsquosjustpickthissmallsettoworkwithfornowandimproveitlater

BreakingUpaSentenceOncewehaveourlexiconweneedawaytobreakupsentencessothatwecanfigureoutwhattheyareInourcasewersquovedefinedasentenceasldquowordsseparatedbyspacesrdquosowereallyjustneedtodothis

stuff=input(gt)

words=stuffsplit()Thatrsquosallwersquollworryaboutfornowbutthis

willworkreallywellforquiteawhile

LexiconTuples

LexiconTuplesOnceweknowhowtobreakupasentenceintowordswejusthavetogothroughthelistofwordsandfigureoutwhatldquotyperdquotheyareTodothatwersquoregoingtouseahandylittlePythonstructurecalledaldquotuplerdquoAtupleisnothingmorethanalistthatyoucanrsquotmodifyItrsquoscreatedbyputtingdatainsideasetofparentheseswithacommalikealistClickheretoviewcodeimage

first_word=(verbgo)

second_word=(directionnorth)

third_word=(directionwest)

sentence=[first_wordsecond_wordthird_word]

Thiscreatesapair(TYPEWORD)thatletsyoulookatthewordanddothingswithitThisisjustanexamplebutthatrsquosbasicallytheendresultYouwanttotakerawinputfromtheusercarveitintowordswithsplitanalyzethosewordstoidentifytheirtypesandfinallymakeasentenceoutofthem

ScanningInputNowyouarereadytowriteyourscannerThisscannerwilltakeastringofrawinputfromauserandreturnasentencethatrsquoscomposedofalistoftupleswiththe(TOKENWORD)pairingsIfawordisnrsquotpartofthelexiconthenitshouldstillreturntheWORDbutsettheTOKENtoanerrortokenTheseerrortokenswilltelluserstheymessedupHerersquoswhereitgetsfunIrsquomnotgoingtotellyouhowtodothisInsteadIrsquomgoingtowritealdquounittestrdquoandyouaregoingtowritethescannersothattheunittestworks

ExceptionsandNumbersThereisonetinythingIwillhelpyouwithfirstandthatrsquosconvertingnumbersInordertodothisthoughwersquoregoingtocheatanduseexceptionsAnexceptionisanerrorthatyougetfromsomefunctionyoumayhaverunWhathappensisyourfunctionldquoraisesrdquoanexceptionwhenitencountersanerrorthenyouhavetohandlethatexceptionForexampleifyoutypethisintoPythonyougetanexceptionClickheretoviewcodeimage

Exercise48PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtint(hell)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

ValueErrorinvalidliteralforint()withbase10hell

ThatValueErrorisanexceptionthattheint()functionthrewbecausewhatyouhandedint()isnotanumberTheint())functioncouldhavereturnedavaluetotellyouithadanerrorbutsinceitonlyreturnsintegersitrsquodhaveahardtimedoingthatItcanrsquotreturn-1sincethatrsquosanumberInsteadoftryingtofigureoutwhattoreturnwhentherersquosanerrortheint()functionraisestheValueErrorexceptionandyoudealwithitYoudealwithanexceptionbyusingthetryandexceptkeywordsex48_convertpy

1defconvert_number(s)

2try

3returnint(s)

4exceptValueError

5returnNoneYouputthecodeyouwanttoldquotryrdquoinside

thetryblockandthenyouputthecodetorunfortheerrorinside

theexceptInthiscasewewanttoldquotryrdquotocallint()onsomething

thatmightbeanumberIfthathasanerrorthenweldquocatchrdquoitand

returnNone

InyourscannerthatyouwriteyoushouldusethisfunctiontotestwhethersomethingisanumberYoushouldalsodoitasthelastthingyoucheckforbeforedeclaringthatwordanerrorword

ATestFirstChallengeTestfirstisaprogrammingtacticwhereyouwriteanautomatedtestthatpretendsthecodeworksthenyouwritethecodetomakethetestactuallyworkThismethodworkswhenyoucanrsquotvisualizehowthecodeisimplementedbutyoucanimaginehowyouhavetoworkwithitForexampleifyouknowhowyouneedtouseanewclassinanothermodulebutyoudonrsquotquiteknowhowtoimplementthatclassyetthenwritethetestfirstYouaregoingtotakeatestIgiveyouanduseittowritethecodethatmakesitworkTodothisexercisefollowthisprocedure1CreateonesmallpartofthetestIgiveyou

2Makesureitrunsandfailssoyouknowthatthetestisactuallyconfirmingafeatureworks

3Gotoyoursourcefilelexiconpyandwritethecodethatmakesthistestpass

4RepeatuntilyouhaveimplementedeverythinginthetestWhenyougettostep3itrsquosalsogoodtocombineourothermethodofwritingcode1Maketheldquoskeletonrdquofunctionorclassthatyouneed

2Writecommentsinsidedescribinghowthatfunctionworks3Writethecodethatdoeswhatthecommentsdescribe4Removeanycommentsthatjustrepeatthecode

ThismethodofwritingcodeiscalledldquopsuedocoderdquoandworkswellifyoudonrsquotknowhowtoimplementsomethingbutyoucandescribeitinyourownwordsCombiningtheldquotestfirstrdquowiththeldquopsuedocoderdquotacticswehavethissimpleprocessforprogramming1Writeabitoftestthatfails

2Writetheskeletonfunctionmoduleclassthetestneeds3Filltheskeletonwithcommentsinyourownwordsexplaininghowitworks

4Replacethecommentswithcodeuntilthetestpasses5Repeat

InthisexerciseyouwillpracticethismethodofworkingbymakingatestIgiveyourunagainstthelexiconpymodule

WhatYouShouldTestHereisthetestcasetestslexicon_testspythatyoushouldusebutdonrsquottypethisinyetClickheretoviewcodeimage

lexicon_testspy

1fromnosetoolsimport

2fromex48importlexicon

3

4

5deftest_directions()

6assert_equal(lexiconscan(north)[(direction

north)])

7result=lexiconscan(northsoutheast)

8assert_equal(result[(directionnorth)

9(directionsouth)

10(directioneast)])

11

12deftest_verbs()

13assert_equal(lexiconscan(go)[(verbgo)])

14result=lexiconscan(gokilleat)

15assert_equal(result[(verbgo)

16(verbkill)

17(verbeat)])

18

19

20deftest_stops()

21assert_equal(lexiconscan(the)[(stopthe)])

22result=lexiconscan(theinof)

23assert_equal(result[(stopthe)

24(stopin)

25(stopof)])

26

27

28deftest_nouns()

29assert_equal(lexiconscan(bear)[(nounbear)])

30result=lexiconscan(bearprincess)

31assert_equal(result[(nounbear)

32(nounprincess)])

33

34deftest_numbers()

35assert_equal(lexiconscan(1234)[(number1234)])

36result=lexiconscan(391234)

37assert_equal(result[(number3)

38(number91234)])

39

40

41deftest_errors()

42assert_equal(lexiconscan(ASDFADFASDF)

43[(errorASDFADFASDF)])

44result=lexiconscan(bearIASprincess)

45assert_equal(result[(nounbear)

46(errorIAS)

47(nounprincess)])Youwillwant

tocreateanewprojectusingtheprojectskeletonjustlikeyoudid

inExercise47Thenyoursquollneedtocreatethistestcaseandthe

lexiconpyfileitwilluseLookatthetopofthetestcasetosee

howitrsquosbeingimportedtofigureoutwhereitgoes

NextfollowtheprocedureIgaveyouandwritealittlebitofthetestcaseatatimeForexampleherersquoshowIrsquoddoit1WritetheimportatthetopGetthattowork

2Createanemptyversionofthefirsttestcasetest_directionsMakesurethatruns

3Writethefirstlineofthetest_directionstestcaseMakeitfail4Gotothelexiconpyfileandcreateanemptyscanfunction5Runthetestandmakesurescanisatleastrunningeventhoughitfails6Fillinpsuedocodecommentsforhowscanshouldworktomaketest_directionspass

7Writethecodethatmatchesthecommentsuntiltest_directionspasses

8Gobacktotest_directionsandwritetherestofthelines9Gobacktoscaninlexiconpyandworkonittomakethisnewtestcodepass

10Onceyoursquovedonethatyouhaveyourfirstpassingtestandyoumoveontothenexttest

AslongasyoukeepfollowingthisprocedureonelittlechunkatatimeyoucansuccessfullyturnalargeproblemintosmallersolvableproblemsItrsquoslikeclimbingamountainbyturningitintoabunchoflittlehills

StudyDrills1Improvetheunittesttomakesureyoutestmoreofthelexicon2Addtothelexiconandthenupdatetheunittest3MakesureyourscannerhandlesuserinputinanycapitalizationandcaseUpdatethetesttomakesurethisactuallyworks

4Findanotherwaytoconvertthenumber5Mysolutionwas37lineslongIsyourslongerShorter

CommonStudentQuestionsWhydoIkeepgettingImportErrorsImporterrorsareusuallycausedbyfourthings1Youdidnrsquotmakean__init__pyinadirectorythathasmodulesinit2Youareinthewrongdirectory3Youareimportingthewrongmodulebecauseyouspelleditwrong4YourPYTHONPATHisnrsquotsettosoyoucanrsquotloadmodulesfromyourcurrentdirectory

Whatrsquosthedifferencebetweentry-exceptandif-elseThe

try-exceptconstructisonlyusedforhandlingexceptionsthatmodulescanthrowItshouldneverbeusedasanalternativetoif-else

IsthereawaytokeepthegamerunningwhiletheuseriswaitingtotypeIrsquomassumingyouwanttohaveamonsterattackusersiftheydonrsquotreactquicklyenoughItispossiblebutitinvolvesmodulesandtechniquesthatareoutsideofthisbookrsquosdomain

Exercise49MakingSentences

WhatweshouldbeabletogetfromourlittlegamelexiconscannerisalistthatlookslikethisClickheretoviewcodeimage

Exercise49PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48importlexicon

gtgtgtlexiconscan(gonorth)

[(verbgo)(directionnorth)]

gtgtgtlexiconscan(killtheprincess)

[(verbkill)(stopthe)(nounprincess)]

gtgtgtlexiconscan(eatthebear)

[(verbeat)(stopthe)(nounbear)]

Thiswillalsoworkonlongersentencessuchaslexiconscan(openthedoorandsmackthebearinthenose)NowletusturnthisintosomethingthegamecanworkwithwhichwouldbesomekindofSentenceclassIfyouremembergradeschoolasentencecanbeasimplestructurelikeSubjectVerbObjectObviouslyitgetsmorecomplexthanthatandyouprobablydidmanydaysofannoyingsentencediagramsforEnglishclassWhatwewantistoturntheprecedinglistsoftuplesintoaniceSentenceobjectthathassubjectverbandobject

MatchandPeekTodothisweneedfivetools

1AwaytoloopthroughthelistofscannedwordsThatrsquoseasy2AwaytoldquomatchrdquodifferenttypesoftuplesthatweexpectinourSubjectVerbObjectsetup

3Awaytoldquopeekrdquoatapotentialtuplesowecanmakesomedecisions4Awaytoldquoskiprdquothingswedonotcareaboutlikestopwords5ASentenceobjecttoputtheresultsin

Wewillbeputtingthesefunctionsinamodulenamedex48parserinafilenamedex48parserpyinordertotestitWeusethepeekfunctiontosay

ldquolookatthenextelementinourtuplelistandthenmatchtotakeoneoffandworkwithitrdquo

TheSentenceGrammarBeforeyoucanwritethecodeyouneedtounderstandhowbasicEnglishsentencegrammarworksInourparserwewanttoproduceaSentenceobjectthathasthreeattributes

SentencesubjectThisisthesubjectofanysentencebutcoulddefaulttoldquoplayerrdquomostofthetimesinceasentenceofldquorunnorthrdquoisimplyingldquoplayerrunnorthrdquoThiswillbeanoun

SentenceverbThisistheactionofthesentenceInldquorunnorthrdquoitwouldbeldquorunrdquoThiswillbeaverb

SentenceobjectThisisanothernounthatreferstowhattheverbisdoneonInourgameweseparateoutdirectionswhichwouldalsobeobjectsInldquorunnorthrdquothewordldquonorthrdquowouldbetheobjectInldquohitbearrdquothewordldquobearrdquowouldbetheobject

OurparserthenhastousethefunctionswedescribedandgivenascannedsentenceconvertitintoanListofSentenceobjectstomatchtheinput

AWordonExceptionsYoubrieflylearnedaboutexceptionsbutnothowtoraisethemThiscodedemonstrateshowtodothatwiththeParserErroratthetopNoticethatitusesclassestogiveitthetypeofExceptionAlsonoticetheuseoftheraisekeywordtoraisetheexceptionInyourtestsyouwillwanttoworkwiththeseexceptionswhichIrsquollshowyouhowtodo

TheParserCodeIfyouwantanextrachallengestoprightnowandtrytowritethisbasedonjustmydescriptionIfyougetstuckyoucancomebackandseehowIdiditbuttryingtoimplementtheparseryourselfisgoodpracticeIwillnowwalkthroughthecodesoyoucanenteritintoyourex48parserpyWestarttheparserwiththeexceptionweneedforaparsingerrorClickheretoviewcodeimage

parserpy

1classParserError(Exception)

2pass

ThisishowyoumakeyourownParserErrorexceptionclassyoucanthrowNextweneedtheSentenceobjectwersquollcreateClickheretoviewcodeimage

parserpy

1classSentence(object)

2

3def__init__(selfsubjectverbobj)

4rememberwetake(nounprincess)tuplesand

convertthem

5selfsubject=subject[1]

6selfverb=verb[1]

7selfobject=obj[1]

TherersquosnothingspecialaboutthiscodesofarYoursquorejustmakingsimpleclassesInourdescriptionoftheproblemweneedafunctionthatcanpeekatalistofwordsandreturnwhattypeofworditisClickheretoviewcodeimage

parserpy

1defpeek(word_list)

2ifword_list

3word=word_list[0]

4returnword[0]

5else

6returnNoneWeneedthisfunctionbecausewersquollhaveto

makedecisionsaboutwhatkindofsentencewersquoredealingwithbased

onwhatthenextwordisThenwecancallanotherfunctionto

consumethatwordandcarryon

ToconsumeawordweusethematchfunctionwhichconfirmsthattheexpectedwordistherighttypetakesitoffthelistandreturnsthewordClickheretoviewcodeimage

parserpy

1defmatch(word_listexpecting)

2ifword_list

3word=word_listpop(0)

4

5ifword[0]==expecting

6returnword

7else

8returnNone

9else

10returnNoneAgainthisisfairlysimplebutmakesure

youunderstandthiscodeAlsomakesureyouunderstandwhyIrsquomdoing

itthiswayIneedtopeekatwordsinthelisttodecidewhatkind

ofsentenceIrsquomdealingwithandthenIneedtomatchthosewordsto

createmySentence

ThelastthingIneedisawaytoskipwordsthatarenrsquotusefultotheSentenceThesearethewordslabeledldquostopwordsrdquo(typestop)thatarewordslikeldquotherdquoldquoandrdquoandldquoardquoClickheretoviewcodeimage

parserpy

1defskip(word_listword_type)

2whilepeek(word_list)==word_type

3match(word_listword_type)Rememberthatskipdoesnrsquot

skiponeworditskipsasmanywordsofthattypeasitfindsThis

makesitsoifsomeonetypesldquoscreamatthebearrdquoyougetldquoscreamrdquo

andldquobearrdquo

ThatrsquosourbasicsetofparsingfunctionsandwiththatwecanactuallyparsejustaboutanytextwewantOurparserisverysimplethoughsotheremainingfunctionsareshortFirstwecanhandleparsingaverbClickheretoviewcodeimage

parserpy

1defparse_verb(word_list)

2skip(word_liststop)

3

4ifpeek(word_list)==verb

5returnmatch(word_listverb)

6else

7raiseParserError(Expectedaverbnext)Weskipany

stopwordsthenpeekaheadtomakesurethenextwordisaldquoverbrdquo

typeIfitrsquosnotthenraisetheParserErrortosaywhyIfitisa

ldquoverbrdquothenmatchitwhichtakesitoffthelistAsimilar

functionhandlessentenceobjectsClickheretoviewcodeimage

parserpy

1defparse_object(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==direction

8returnmatch(word_listdirection)

9else

10raiseParserError(Expectedanounordirectionnext)

Againskipthestopwordspeekaheadanddecideifthesentenceis

correctbasedonwhatrsquosthereIntheparse_objectfunctionthough

weneedtohandlebothldquonounrdquoandldquodirectionrdquowordsaspossible

objectsSubjectsarethensimilaragainbutsincewewanttohandle

theimpliedldquoplayerrdquonounwehavetousepeekClickheretoview

codeimage

parserpy

1defparse_subject(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==verb

8return(nounplayer)

9else

10raiseParserError(Expectedaverbnext)Withthat

alloutofthewayandreadyourfinalparse_sentencefunctionis

verysimpleClickheretoviewcodeimage

parserpy

1defparse_sentence(word_list)

2subj=parse_subject(word_list)

3verb=parse_verb(word_list)

4obj=parse_object(word_list)

5

6returnSentence(subjverbobj)

PlayingwiththeParserToseehowthisworksyoucanplaywithitlikethis

ToseehowthisworksyoucanplaywithitlikethisClickheretoviewcodeimage

Exercise49aPythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48parserimport

gtgtgtx=parse_sentence([(verbrun)(directionnorth)])

gtgtgtxsubject

player

gtgtgtxverb

run

gtgtgtxobject

north

gtgtgtx=parse_sentence([(nounbear)(verbeat)(stop

the)

(nounhoney)])

gtgtgtxsubject

bear

gtgtgtxverb

eat

gtgtgtxobject

honey

TrytomapsentencestothecorrectpairingsinasentenceForexamplehowwouldyousayldquothebearrunsouthrdquo

WhatYouShouldTestForExercise49writeacompletetestthatconfirmseverythinginthiscodeisworkingPutthetestintestsparser_testspysimilartothetestfilefromthelastexerciseThatincludesmakingexceptionshappenbygivingtheparserbadsentencesCheckforanexceptionbyusingthefunctionassert_raisesfromthenosedocumentationLearnhowtousethissoyoucanwriteatestthatisexpectedtofailwhichisveryimportantintestingLearnaboutthisfunction(andothers)byreadingthenosedocumentationWhenyouaredoneyoushouldknowhowthisbitofcodeworksandhowtowriteatestforotherpeoplersquoscodeeveniftheydonotwantyoutoTrustmeitrsquosaveryhandyskilltohave

StudyDrills

StudyDrills1Changetheparse_methodsandtrytoputthemintoaclassratherthanusethemjustasmethodsWhichdesigndoyoulikebetter

2Maketheparsermoreerror-resistantsothatyoucanavoidannoyingyourusersiftheytypewordsyourlexicondoesnrsquotunderstand

3Improvethegrammarbyhandlingmorethingslikenumbers4ThinkabouthowyoumightusethisSentenceclassinyourgametodomorefunthingswithauserrsquosinput

CommonStudentQuestionsIcanrsquotseemtomakeassert_raisesworkrightMakesureyouarewritingassert_raises(exceptioncallableparameters)andnotwritingassert_raises(exceptioncallable(parameters))Noticehowthesecondformiscallingthefunctionthenpassingtheresulttoassert_raiseswhichiswrongYouhavetopassthefunctiontocallanditsargumentstoassert_raises

Exercise50YourFirstWebsite

ThesefinalthreeexerciseswillbeveryhardandyoushouldtakeyourtimewiththemInthisfirstoneyoursquollbuildasimplewebversionofoneofyourgamesBeforeyouattemptthisexerciseyoumusthavecompletedExercise46successfullyandhaveaworkingpipinstalledsuchthatyoucaninstallpackagesandknowhowtomakeaskeletonprojectdirectoryIfyoudonrsquotrememberhowtodothisgobacktoExercise46anddoitalloveragain

InstallingflaskBeforecreatingyourfirstwebapplicationyoursquollfirstneedtoinstalltheldquowebframeworkrdquocalledflaskThetermldquoframeworkrdquogenerallymeansldquosomepackagethatmakesiteasierformetodosomethingrdquoIntheworldofwebapplicationspeoplecreateldquowebframeworksrdquotocompensateforthedifficultproblemstheyrsquoveencounteredwhenmakingtheirownsitesTheysharethesecommonsolutionsintheformofapackageyoucandownloadtobootstrapyourownprojectsInourcasewersquollbeusingtheflaskframeworkbuttherearemanymanymanyothersyoucanchoosefromFornowlearnflaskthenbranchouttoanotheronewhenyoursquoreready(orjustkeepusingflasksinceitrsquosgoodenough)UsingpipinstallflaskClickheretoviewcodeimage

$sudopipinstallflask

[sudo]passwordforzedshaw

Downloadingunpackingflask

Runningsetuppyegg_infoforpackageflask

Installingcollectedpackagesflask

Runningsetuppyinstallforflask

Successfullyinstalledflask

Cleaningup

ThiswillworkonLinuxandmacOScomputersbutonWindowsjustdropthesudopartofthepipinstallcommandanditshouldworkIfnotgobacktoExercise46andmakesureyoucandoitreliably

MakeaSimpleldquoHelloWorldrdquoProject

NowyoursquoregoingtomakeaninitialverysimpleldquoHelloWorldrdquowebapplicationandprojectdirectoryusingflaskFirstmakeyourprojectdirectoryClickheretoviewcodeimage

$cdprojects

$mkdirgothonweb

$cdgothonweb

$mkdirbingothonwebtestsdocstemplates

$touchgothonweb__init__py

$touchtests__init__py

YoursquollbetakingthegamefromExercise43andmakingitintoawebapplicationsothatrsquoswhyyoursquorecallingitgothonwebBeforeyoudothatweneedtocreatethemostbasicflaskapplicationpossiblePutthefollowingcodeintoapppyClickheretoviewcodeimage

ex50py

1fromflaskimportFlask

2app=Flask(__name__)

3

4approute()

5defhello_world()

6returnHelloWorld

7

8if__name__==__main__

9apprun()ThenruntheapplicationlikethisClickhereto

viewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)Finally

useyourwebbrowserandgotohttplocalhost5000andyoushould

seetwothingsFirstinyourbrowseryoursquollseeHelloworld

SecondyoursquollseeyourTerminalwithnewoutputlikethisClick

heretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

127001ndashndash[22Feb2017142850]GETHTTP11200ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

ThosearelogmessagesthatflaskprintsoutsoyoucanseethattheserverisworkingandwhatthebrowserisdoingbehindthescenesThelogmessageshelpyoudebugandfigureoutwhenyouhaveproblemsForexampleitrsquossayingthatyourbrowsertriedtogetfaviconicobutthatfiledidnrsquotexistsoit

returnedthe404NotFoundstatuscodeIhavenrsquotexplainedthewayanyofthiswebstuffworksyetbecauseIwanttogetyousetupandreadytorollsothatIcanexplainitbetterinthenexttwoexercisesToaccomplishthisIrsquollhaveyoubreakyourflaskapplicationinvariouswaysandthenrestructureitsothatyouknowhowitrsquossetup

WhatrsquosGoingOnHerersquoswhatrsquoshappeningwhenyourbrowserhitsyourapplication

1YourbrowsermakesanetworkconnectiontoyourowncomputerwhichiscalledlocalhostandisastandardwayofsayingldquowhatevermyowncomputeriscalledonthenetworkrdquoItalsousesport5000

2OnceitconnectsitmakesanHTTPrequesttotheapppyapplicationandasksfortheURLwhichiscommonlythefirstURLonanywebsite

3InsideapppyyoursquovegotalistofURLsandwhatfunctionstheymatchTheonlyonewehaveistheindexmappingThismeansthatwheneversomeonegoestowithabrowserflaskwillfindthedefindexandrunittohandletherequest

4NowthatflaskhasfounddefindexitcallsittoactuallyhandletherequestThisfunctionrunsandsimplyreturnsastringforwhatflaskshouldsendtothebrowser

5Finallyflaskhashandledtherequestandsendsthisresponsetothebrowserwhichiswhatyouareseeing

MakesureyoureallyunderstandthisDrawupadiagramofhowthisinformationflowsfromyourbrowsertoflaskthentodefindexandbacktoyourbrowser

FixingErrorsFirstdeleteline8whereyouassignthegreetingvariablethenhitrefreshinyourbrowserThenuseCTRL-CtokillflaskandstartitagainOnceitrsquosrunningagainrefreshyourbrowserandyoushouldseeanldquoInternalServerErrorrdquoBackinyourTerminalyoursquollseethis([VENV]isthepathtoyourvenvsdirectory)Clickheretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

[2017ndash02ndash22143554256]ERRORinappExceptionon[GET]

Traceback(mostrecentcalllast)

File[VENV]site-packagesflaskapppy

line1982inwsgi_app

response=selffull_dispatch_request()

File[VENV]site-packagesflaskapppy

line1614infull_dispatch_request

rv=selfhandle_user_exception(e)

File[VENV]site-packagesflaskapppy

line1517inhandle_user_exception

reraise(exc_typeexc_valuetb)

File[VENV]site-packagesflask_compatpy

line33inreraise

raisevalue

File[VENV]site-packagesflaskapppy

line1612infull_dispatch_request

rv=selfdispatch_request()

File[VENV]site-packagesflaskapppy

line1598indispatch_request

returnselfview_functions[ruleendpoint](reqview_args)

Fileapppyline8inindex

returnrender_template(indexhtmlgreeting=greeting)

NameErrornamegreetingisnotdefined

127001ndashndash[22Feb2017143554]GETHTTP11500ndash

ThisworkswellenoughbutyoucanalsorunflaskinldquodebuggermoderdquoThiswillgiveyouabettererrorpageandmoreusefulinformationTheproblemwithdebuggermodeisitrsquosnotsafetorunontheinternetsoyouhavetoexplicitlyturnitonlikethisClickheretoviewcodeimage

(lpthw)$exportFLASK_DEBUG=1

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

Restartingwithstat

Debuggerisactive

Debuggerpincode222ndash752ndash342

Afterthisyouhitrefreshinyourbrowserandyougetamuchmoredetailedpagewithinformationyoucanusetodebugtheapplicationandaliveconsoletoworkwithtofindoutmore

WarningItrsquostheflasklivedebuggingconsoleandtheimprovedoutputthatmakesdebugmodesodangerousontheinternetWiththisinformationanattackercancompletelycontrolyourmachineremotelyIfyoueverdoplaceyourwebapplicationontheinternetdonotactivatedebuggermodeInfactIwouldavoid

makingFLASK_DEBUGeasytoactivateItrsquostemptingtosimplyhackthisstartupsothatyousaveastepduringdevelopmentbutthenthathackwillgetontoyourwebserveranditrsquollturnintoarealhacknotjustsomethinglazyyoudidonenightwhenyouweretired

CreateBasicTemplatesYoucanbreakyourflaskapplicationbutdidyounoticethatldquoHelloWorldrdquoisnrsquotaverygoodHTMLpageThisisawebapplicationandassuchitneedsaproperHTMLresponseTodothatyouwillcreateasimpletemplatethatsaysldquoHelloWorldrdquoinabiggreenfontThefirststepistocreateatemplatesindexhtmlfilethatlookslikethisClickheretoviewcodeimage

indexhtml

lthtmlgt

ltheadgt

lttitlegtGothonsOfPlanetPercal25lttitlegt

ltheadgt

ltbodygt

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

ltbodygt

lthtmlgtIfyouknowwhatHTMListhenthisshouldlookfairly

familiarIfnotresearchHTMLandtrywritingafewwebpagesby

handsoyouknowhowitworksThisHTMLfilehoweverisa

templatewhichmeansthatflaskwillfillinldquoholesrdquointhetext

dependingonvariablesyoupassintothetemplateEveryplaceyou

see$greetingwillbeavariableyoursquollpasstothetemplatethat

altersitscontents

TomakeyourapppydothisyouneedtoaddsomecodetotellflaskwheretoloadthetemplateandtorenderitTakethatfileandchangeitlikethisClickheretoviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3

4app=Flask(__name__)

5

6approute()

7defindex()

8greeting=HelloWorld

9returnrender_template(indexhtmlgreeting=greeting)

10

11if__name__==__main__

12apprun()Paycloseattentiontothenewrendervariable

andhowIchangedthelastlineofindexGETsoitreturns

renderindex()passinginyourgreetingvariable

OnceyouhavethatinplacereloadthewebpageinyourbrowserandyoushouldseeadifferentmessageingreenYoushouldalsobeabletodoaViewSourceonthepageinyourbrowsertoseethatitisvalidHTMLThismayhaveflownbyyouveryfastsoletmeexplainhowatemplateworks1Inyourapppyyoursquoveimportedanewfunctionnamedrender_templateatthetop

2Thisrender_templateknowshowtoloadhtmlfilesoutofthetemplatesdirectorybecausethatisthedefaultmagicsettingforaflaskapplication

3Laterinyourcodewhenthebrowserhitsthedefindexinsteadofjustreturningthestringgreetingyoucallrender_templateandpassthegreetingtoitasavariable

4Thisrender_templatemethodthenloadsthetemplatesindexhtmlfile(eventhoughyoudidnrsquotexplicitlysaytemplates)andprocessesit

5InthistemplatesindexhtmlfileyouhavewhatlookslikenormalHTMLbutthentherersquosldquocoderdquoplacedbetweentwokindsofmarkersOneiswhichmarkspiecesofldquoexecutablecoderdquo(if-statementsfor-loopsetc)TheotheriswhichmarksvariablestobeconvertedintotextandplacedintotheHTMLoutputTheexecutablecodedoesnrsquotshowupintheHTMLTolearnmoreaboutthistemplatelanguagereadtheJinja2documentation

TogetdeeperintothischangethegreetingvariableandtheHTMLtoseewhateffectithasAlsocreateanothertemplatenamedtemplatesfoohtmlandrenderthatlikebefore

StudyDrills1Readthedocumentationathttpflaskpocooorgdocs012whichisthesameastheflaskproject

2Experimentwitheverythingyoucanfindthereincludingtheirexamplecode

3ReadaboutHTML5andCSS3andmakesomeotherhtmlandcssfilesforpractice

4IfyouhaveafriendwhoknowsDjangoandiswillingtohelpyouthenconsiderdoingExercises5051and52inDjangoinsteadtoseewhatthatrsquoslike

CommonStudentQuestionsIcanrsquotseemtoconnecttohttplocalhost5000Tryhttp1270015000instead

WhatisthedifferencebetweeflaskandwebpyNodifferenceIsimplyldquolockedrdquowebpyataparticularversionsothatitwouldbeconsistentforstudentsthennameditflaskLaterversionsofwebpymightbedifferentfromthisversion

Icanrsquotfindindexhtml(orjustaboutanything)YouprobablyaredoingcdbinfirstandthentryingtoworkwiththeprojectDonotdothisAllofthecommandsandinstructionsassumeyouareonedirectoryabovebinsoifyoucanrsquottypepython36apppythenyouareinthewrongdirectory

Whydoweassigngreeting=greetingwhenwecallthetemplateYouarenotassigningtogreetingYouaresettinganamedparametertogivetothetemplateItrsquossortofanassignmentbutitonlyaffectsthecalltothetemplatefunction

Icanrsquotuseport5000onmycomputerYouprobablyhaveananti-virusprograminstalledthatisusingthatportTryadifferentport

AfterinstallingflaskIgetImportErrorNomodulenamedwebYoumostlikelyhavemultipleversionsofpythoninstalledandareusingthewrongoneoryoudidnrsquotdotheinstall

correctlybecauseofanoldversionofpipTryuninstallingflaskandreinstallingitIfthatdoesnrsquotworkmaketriplesureyoursquoreusingtherightversionofpython

Exercise51GettingInputfromaBrowser

WhileitrsquosexcitingtoseethebrowserdisplayldquoHelloWorldrdquoitrsquosevenmoreexcitingtolettheusersubmittexttoyourapplicationfromaformInthisexercisewersquollimproveourstarterwebapplicationbyusingformsandstoringinformationaboutusersintotheirldquosessionsrdquo

HowtheWebWorksTimeforsomeboringstuffYouneedtounderstandabitmoreabouthowthewebworksbeforeyoucanmakeaformThisdescriptionisnrsquotcompletebutitrsquosaccurateandwillhelpyoufigureoutwhatmightbegoingwrongwithyourapplicationAlsocreatingformswillbeeasierifyouknowwhattheydoIrsquollstartwithasimplediagramthatshowsyouthedifferentpartsofawebrequestandhowtheinformationflows

IrsquovelabeledthelineswithletterssoIcanwalkyouthrougharegularrequestprocess1Youtypeintheurlhttptestcomintoyourbrowseranditsendstherequestonline(A)toyourcomputerrsquosnetworkinterface

2Yourrequestgoesoutovertheinternetonline(B)andthentotheremotecomputeronline(C)wheremyserveracceptstherequest

3Oncemycomputeracceptsitmywebapplicationgetsitonline(D)andmyPythoncoderunstheindexGEThandler

4TheresponsecomesoutofmyPythonserverwhenIreturnitandit

goesbacktoyourbrowseroverline(D)again5Theserverrunningthissitetakestheresponseoffline(D)thensendsitbackovertheinternetonline(C)

6Theresponsefromtheserverthencomesofftheinternetonline(B)andyourcomputerrsquosnetworkinterfacehandsittoyourbrowseronline(A)

7FinallyyourbrowserthendisplaystheresponseInthisdescriptionthereareafewtermsyoushouldknowsothatyouhaveacommonvocabularytoworkwithwhentalkingaboutyourwebapplicationBrowserThesoftwarethatyoursquoreprobablyusingeverydayMostpeopledonrsquotknowwhatabrowserreallydoesTheyjustcallbrowsersldquotheinternetrdquoItsjobistotakeaddresses(likehttptestcom)youtypeintotheURLbarthenusethatinformationtomakerequeststotheserveratthataddress

AddressThisisnormallyaURL(UniformResourceLocator)likehttptestcomandindicateswhereabrowsershouldgoThefirstparthttpindicatestheprotocolyouwanttouseinthiscaseldquoHyper-TextTransportProtocolrdquoYoucanalsotryftpibiblioorgtoseehowldquoFileTransportProtocolrdquoworksThehttptestcompartistheldquohostnamerdquoahumanreadableaddressyoucanrememberandwhichmapstoanumbercalledanIPaddresssimilartoatelephonenumberforacomputerontheinternetFinallyURLscanhaveatrailingpathlikethebookpartofhttptestcombookwhichindicatesafileorsomeresourceontheservertoretrievewitharequestTherearemanyotherpartsbutthosearethemainones

ConnectionOnceabrowserknowswhatprotocolyouwanttouse(http)whatserveryouwanttotalkto(httptestcom)andwhatresourceonthatservertogetitmustmakeaconnectionThebrowsersimplyasksyouroperatingsystem(OS)toopenaldquoportrdquotothecomputerusuallyport80WhenitworkstheOShandsbacktoyourprogramsomethingthatworkslikeafilebutisactuallysendingandreceivingbytesoverthenetworkwiresbetweenyourcomputerandtheothercomputerathttptestcomThisisalsothesamethingthathappenswithhttplocalhost8080butinthiscaseyoursquoretellingthebrowsertoconnecttoyourowncomputer(localhost)anduseport8080ratherthanthedefaultof80Youcouldalsodohttptestcom80andgetthesameresultexceptyoursquoreexplicitlysayingtouseport80insteadoflettingitbethatbydefault

RequestYourbrowserisconnectedusingtheaddressyougaveNowitneedstoaskfortheresourceitwants(oryouwant)ontheremoteserverIfyougavebookattheendoftheURLthenyouwantthefile(resource)atbookandmostserverswillusetherealfilebookindexhtmlbutpretenditdoesnrsquotexistWhatthebrowserdoestogetthisresourceissendarequesttotheserverIwonrsquotgetintoexactlyhowitdoesthisbutjustunderstandthatithastosendsomethingtoquerytheserverfortherequestTheinterestingthingisthattheseldquoresourcesrdquodonrsquothavetobefilesForinstancewhenthebrowserinyourapplicationasksforsomethingtheserverisreturningsomethingyourPythoncodegenerated

ServerTheserveristhecomputerattheendofabrowserrsquosconnectionthatknowshowtoansweryourbrowserrsquosrequestsforfilesresourcesMostwebserversjustsendfilesandthatrsquosactuallythemajorityoftrafficButyoursquoreactuallybuildingaserverinPythonthatknowshowtotakerequestsforresourcesandthenreturnstringsthatyoucraftusingPythonWhenyoudothiscraftingyouarepretendingtobeafiletothebrowserbutreallyitrsquosjustcodeAsyoucanseefromExercise50italsodoesnrsquottakemuchcodetocreatearesponse

ResponseThisistheHTML(CSSJavaScriptorimages)yourserverwantstosendbacktothebrowserastheanswertothebrowserrsquosrequestInthecaseoffilesitjustreadsthemoffthediskandsendsthemtothebrowserbutitwrapsthecontentsofthediskinaspecialldquoheaderrdquosothebrowserknowswhatitrsquosgettingInthecaseofyourapplicationyoursquorestillsendingthesamethingincludingtheheaderbutyougeneratethatdataontheflywithyourPythoncode

ThatisthefastestcrashcourseinhowawebbrowseraccessesinformationonserversontheinternetItshouldworkwellenoughforyoutounderstandthisexercisebutifnotreadaboutitasmuchasyoucanuntilyougetitAreallygoodwaytodothatistotakethediagramandbreakdifferentpartsofthewebapplicationyoudidinExercise50Ifyoucanbreakyourwebapplicationinpredictablewaysusingthediagramyoursquollstarttounderstandhowitworks

HowFormsWorkThebestwaytoplaywithformsistowritesomecodethatacceptsformdataandthenseewhatyoucandoTakeyourapppyfileandmakeitlooklikethis

Clickheretoviewcodeimage

form_testpy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hello)

8defindex()

9name=requestargsget(nameNobody)

10

11ifname

12greeting=fHelloname

13else

14greeting=HelloWorld

15

16returnrender_template(indexhtmlgreeting=greeting)

17

18if__name__==__main__

19apprun()Restartit(hitCTRL-Candthenrunitagain)to

makesureitloadsagainthenwithyourbrowsergoto

httplocalhost5000hellowhichshoulddisplayldquoIjustwantedto

sayHelloNobodyrdquoNextchangetheURLinyourbrowserto

httplocalhost5000helloname=Frankandyoursquollseeitsay

ldquoHelloFrankrdquoFinallychangethename=Frankparttobeyourname

Nowitrsquossayinghellotoyou

LetrsquosbreakdownthechangesImadetoyourscript1InsteadofjustastringforgreetingIrsquomnowusingrequestargstogetdatafromthebrowserThisisasimpledictthatcontainstheformvaluesaskey=valuepairs

2Ithenconstructthegreetingfromthenewnamewhichshouldbeveryfamiliartoyoubynow

3EverythingelseaboutthefileisthesameasbeforeYoursquorealsonotrestrictedtojustoneparameterontheURLChangethisexampletogivetwovariableslikethishttplocalhost5000helloname=Frankampgreet=HolaThenchangethecodetogetnameandgreetlikethisClickheretoviewcodeimage

greet=requestargsget(greetHello)

greeting=fgreetname

greeting=fgreetname

YoushouldalsotrynotgivingthegreetandnameparametersontheURLYoursquollsimplysendyourbrowsertohttplocalhost5000hellotoseethattheindexnowdefaultstoldquoNobodyrdquofornameandldquoHellordquoforgreet

CreatingHTMLFormsPassingtheparametersontheURLworksbutitrsquoskindofuglyandnoteasytouseforregularpeopleWhatyoureallywantisaldquoPOSTformrdquowhichisaspecialHTMLfilethathasaltformgttaginitThisformwillcollectinformationfromtheuserthensendittoyourwebapplicationjustlikeyoudidaboveLetrsquosmakeaquickonesoyoucanseehowitworksHerersquosthenewHTMLfileyouneedtocreateintemplateshello_formhtmlClickheretoviewcodeimage

hello_formhtml

lthtmlgt

ltheadgt

lttitlegtSampleWebFormlttitlegt

ltheadgt

ltbodygt

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

ltbodygt

lthtmlgtYoushouldthenchangeapppytolooklikethisClickhere

toviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hellomethods=[POSTGET])

8defindex()

9greeting=HelloWorld

10

11ifrequestmethod==POST

12name=requestform[name]

13greet=requestform[greet]

14greeting=fgreetname

15returnrender_template(indexhtmlgreeting=greeting)

16else

17returnrender_template(hello_formhtml)

18

19

20if__name__==__main__

21apprun()Onceyoursquovegotthosewrittenupsimplyrestart

thewebapplicationagainandhititwithyourbrowserlikebefore

ThistimeyoursquollgetaformaskingyouforldquoAGreetingrdquoandldquoYourNamerdquoWhenyouhittheSubmitbuttonontheformitwillgiveyouthesamegreetingyounormallygetbutthistimelookattheURLinyourbrowserSeehowitrsquoshttplocalhost5000helloeventhoughyousentinparametersThepartofthehello_formhtmlfilethatmakesthisworkisthelinewithltformaction=hellomethod=POSTgtThistellsyourbrowserto1Collectdatafromtheuserusingtheformfieldsinsidetheform

2SendthemtotheserverusingaPOSTtypeofrequestwhichisjustanotherbrowserrequestthatldquohidesrdquotheformfields

3SendthattothehelloURL(asshownintheaction=hellopart)

YoucanthenseehowthetwoltinputgttagsmatchthenamesofthevariablesinyournewcodeAlsonoticethatinsteadofjustaGETmethodinsideclassindexIhaveanothermethodPOSTHowthisnewapplicationworksisasfollows1Yourrequestgoestoindex()likenormalexceptnowthereisanif-statementthatcheckstherequestmethodforeitherPOSTorGETmethodsThisishowthebrowsertellsapppythatarequestiseitheraformsubmissionorURLparameters

2IfrequestmethodisPOSTthenyouprocesstheformasifitwerefilledoutandsubmittedreturningthepropergreeting

3Ifrequestmethodisanythingelsethenyousimplyreturnthehello_formhtmlfortheusertofillout

AsanexercisegointothetemplatesindexhtmlfileandaddalinkbacktojusthellosothatyoucankeepfillingouttheformandseeingtheresultsMakesureyoucanexplainhowthislinkworksandhowitrsquoslettingyoucyclebetweentemplatesindexhtmlandtemplateshello_formhtmlandwhatrsquosbeingruninsidethislatestPythoncode

CreatingaLayoutTemplateWhenyouworkonyourgameinthenextexerciseyoursquollneedtomakeabunchoflittleHTMLpagesWritingafullwebpageeachtimewillquicklybecometediousLuckilyyoucancreatealdquolayoutrdquotemplateorakindofshellthatwillwrapallyourotherpageswithcommonheadersandfootersGoodprogrammerstrytoreducerepetitionsolayoutsareessentialforbeingagoodprogrammerChangetemplatesindexhtmltobelikethisClickheretoviewcodeimage

index_laid_outhtml

extendslayouthtml

blockcontent

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

endblock

Thenchangetemplateshello_formhtmltobelikethisClickheretoviewcodeimage

hello_form_laid_outhtml

extendslayouthtml

blockcontent

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

endblock

AllwersquoredoingisstrippingouttheldquoboilerplaterdquoatthetopandthebottomwhichisalwaysoneverypageWersquollputthatbackintoasingletemplateslayouthtmlfilethathandlesitforusfromnowonOnceyouhavethosechangescreateatemplateslayouthtmlfilewiththisinitClickheretoviewcodeimage

layouthtml

lthtmlgt

ltheadgt

lttitlegtGothonsFromPlanetPercal25lttitlegt

ltheadgt

ltbodygt

blockcontent

endblock

ltbodygt

lthtmlgtThisfilelookslikearegulartemplateexceptthatitrsquos

goingtobepassedthecontentsoftheothertemplatesandusedto

wrapthemAnythingyouputinheredoesnrsquotneedtobeintheother

templatesYourotherHTMLtemplateswillbeinsertedintothe

blockcontentsectionflaskknowstousethislayouthtmlasthe

layoutbecauseyouputextendslayouthtmlatthetopofyour

templates

WritingAutomatedTestsforFormsItrsquoseasytotestawebapplicationwithyourbrowserbyjusthittingrefreshbutcomeonwersquoreprogrammershereWhydosomerepetitivetaskwhenwecanwritesomecodetotestourapplicationWhatyoursquoregoingtodonextiswritealittletestforyourwebapplicationformbasedonwhatyoulearnedinExercise

47IfyoudonrsquotrememberExercise47readitagainCreateanewfilenamedtestsapp_testspywiththisClickheretoviewcodeimage

app_testspy

1fromnosetoolsimport

2fromappimportapp

3

4appconfig[TESTING]=True

5web=apptest_client()

6

7deftest_index()

8rv=webget(follow_redirects=True)

9assert_equal(rvstatus_code404)

10

11rv=webget(hellofollow_redirects=True)

12assert_equal(rvstatus_code200)

13assert_in(bFillOutThisFormrvdata)

14

15data=nameZedgreetHola

16rv=webpost(hellofollow_redirects=Truedata=data)

17assert_in(bZedrvdata)

18assert_in(bHolarvdata)Finallyusenoseteststorun

thistestsetupandtestyourwebapplication$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0059s

OK

WhatIrsquomdoinghereisIrsquomactuallyimportingthewholeapplicationfromtheapppymodulethenrunningitmanuallyTheflaskframeworkhasaverysimpleAPIforprocessingrequestswhichlookslikethisClickheretoviewcodeimage

data=nameZedgreetHola

rv=webpost(hellofollow_redirects=Truedata=data)Thismeans

youcansendaPOSTrequestusingthepost()methodandthengiveit

theformdataasadictEverythingelseworksthesameastesting

webget()requests

Inthetestsapp_testspyautomatedtestIrsquomfirstmakingsuretheURLreturnsaldquo404NotFoundrdquoresponsesinceitactuallydoesnrsquotexistThenIrsquomcheckingthathelloworkswithbothaGETandaPOSTformFollowing

thetestshouldbefairlysimpleevenifyoumightnottotallyknowwhatrsquosgoingonTakesometimestudyingthislatestapplicationespeciallyhowtheautomatedtestingworksMakesureyouunderstandhowIimportedtheapplicationfromapppyandranitdirectlyfortheautomatedtestThisisanimportanttrickthatwillleadtomorelearning

StudyDrills1ReadevenmoreaboutHTMLandgivethesimpleformabetterlayoutIthelpstodrawwhatyouwanttodoonpaperandthenimplementitwithHTML

2Thisoneishardbuttrytofigureouthowyoursquoddoafileuploadformsothatyoucanuploadanimageandsaveittothedisk

3Thisisevenmoremind-numbingbutgofindtheHTTPRFC(whichisthedocumentthatdescribeshowHTTPworks)andreadasmuchofitasyoucanItisreallyboringbutcomesinhandyonceinawhile

4ThiswillalsobereallydifficultbutseeifyoucanfindsomeonetohelpyousetupawebserverlikeApacheNginxorthttpdTrytoserveacoupleofyourhtmlandcssfileswithitjusttoseeifyoucanDonrsquotworryifyoucanrsquotWebserverskindofsuck

5Takeabreakafterthisandjusttrymakingasmanydifferentwebapplicationsasyoucan

BreakingItThisisagreatplacetofigureouthowtobreakwebapplicationsYoushouldexperimentwiththefollowing

1HowmuchdamagecanyoudowiththeFLASK_DEBUGsettingonBecarefulthatyoudonrsquotwipeyourselfoutdoingthis

2LetrsquossayyoudonrsquothavedefaultparametersfortheformsWhatcouldgowrong

3YoursquorecheckingforPOSTandthenldquoanythingelserdquoYoucanusethecurlcommandlinetooltogeneratedifferentrequesttypesWhathappens

Exercise52TheStartofYourWebGame

WersquorecomingtotheendofthebookandinthisexerciseIrsquomgoingtoreallychallengeyouWhenyoursquoredoneyoursquollbeareasonablycompetentPythonbeginnerYoursquollstillneedtogothroughafewmorebooksandwriteacouplemoreprojectsbutyoursquollhavetheskillstocompletethemTheonlyobstacleswillbetimemotivationandresourcesInthisexercisewewonrsquotmakeacompletegamebutinsteadwersquollmakeanldquoenginerdquothatcanrunthegamefromExercise47inthebrowserThiswillinvolverefactoringExercise43mixinginthestructurefromExercise47addingautomatedtestsandfinallycreatingawebenginethatcanrunthegamesThisexercisewillbehugeandIpredictyoucouldspendanywherefromaweektomonthsonitbeforemovingonItrsquosbesttoattackitinlittlechunksanddoabitanighttakingyourtimetomakeeverythingworkbeforemovingon

RefactoringtheExercise43GameYoursquovebeenalteringthegothonwebprojectfortwoexercisesandyoursquolldoitonemoretimeinthisexerciseTheskillyoursquorelearningiscalledldquorefactoringrdquoorasIliketocallitldquofixingstuffrdquoRefactoringisatermprogrammersusetodescribetheprocessoftakingoldcodeandchangingittohavenewfeaturesorjusttocleanitupYoursquovebeendoingthiswithoutevenknowingitasitrsquossecondnaturetobuildingsoftwareWhatyoursquolldointhispartistaketheideasfromExercise47ofatestableldquomaprdquoofRoomsandthegamefromExercise43andcombinethemtogethertocreateanewgamestructureItwillhavethesamecontentjustldquorefactoredrdquotohaveabetterstructureThefirststepistograbthecodefromex47gamepycopyittogothonwebplanispherepycopythetestsex47_testspyfiletotestsplanisphere_testspyandrunnosetestsagaintomakesureitkeepsworkingThewordldquoplanisphererdquoisjustasynonymforldquomaprdquowhichavoidsPythonrsquosbuilt-inmapfunctionThethesaurusisyourfriend

WarningFromnowonIwonrsquotshowyoutheoutputofatestrunJustassumethatyoushouldbedoingitanditrsquolllookliketheprecedingunlessyouhaveanerror

OnceyouhavethecodefromExercise47copiedoveritrsquostimetorefactorittohavetheExercise43mapinitIrsquomgoingtostartoffbylayingdownthebasicstructureandthenyoursquollhaveanassignmenttomaketheplanispherepyfileandtheplanisphere_testspyfilecompleteLayoutthebasicstructureofthemapusingtheRoomclassasitisnowClickheretoviewcodeimage

planispherepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)

13

14

15central_corridor=Room(CentralCorridor

16

17TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyed

18yourentirecrewYouarethelastsurvivingmemberandyour

last

19missionistogettheneutrondestructbombfromtheWeapons

Armoryput

20itinthebridgeandblowtheshipupaftergettingintoan

escapepod

21

22YourerunningdownthecentralcorridortotheWeaponsArmory

whena

23Gothonjumpsoutredscalyskindarkgrimyteethandevil

clown

24costumeflowingaroundhishatefilledbodyHesblocking

thedoorto

25theArmoryandabouttopullaweapontoblastyou

26)

27

28

29laser_weapon_armory=Room(LaserWeaponArmory

30

31LuckyforyoutheymadeyoulearnGothoninsultsinthe

academyYou

32telltheoneGothonjokeyouknowLbhezbgurevffbsngjura

furfvgf

33nebhaqgurubhfrfurfvgfnebhaqgurubhfrTheGothon

stopstries

34nottolaughthenbustsoutlaughingandcantmoveWhile

hes

35laughingyourunupandshoothimsquareintheheadputting

himdown

36thenjumpthroughtheWeaponArmorydoor

37

38YoudoadiverollintotheWeaponArmorycrouchandscanthe

roomfor

39moreGothonsthatmightbehidingItsdeadquiettoo

quietYou

40standupandruntothefarsideoftheroomandfindthe

neutronbomb

41initscontainerTheresakeypadlockontheboxandyou

needthe

42codetogetthebomboutIfyougetthecodewrong10times

thenthe

43lockclosesforeverandyoucantgetthebombThecodeis3

digits

44)

45

46

47the_bridge=Room(TheBridge

48

49Thecontainerclicksopenandthesealbreakslettinggas

outYou

50grabtheneutronbombandrunasfastasyoucantothebridge

whereyou

51mustplaceitintherightspot

52

53YouburstontotheBridgewiththenetrondestructbombunder

yourarm

54andsurprise5Gothonswhoaretryingtotakecontrolofthe

shipEach

55ofthemhasanevenuglierclowncostumethanthelastThey

havent

56pulledtheirweaponsoutyetastheyseetheactivebomb

underyourarm

57anddontwanttosetitoff

58)

59

60

61escape_pod=Room(EscapePod

62

63Youpointyourblasteratthebombunderyourarmandthe

Gothonsput

64theirhandsupandstarttosweatYouinchbackwardtothe

dooropen

65itandthencarefullyplacethebombonthefloorpointing

your

66blasteratitYouthenjumpbackthroughthedoorpunchthe

close

67buttonandblastthelocksotheGothonscantgetoutNow

thatthe

68bombisplacedyouruntotheescapepodtogetoffthistin

can

69

70Yourushthroughtheshipdesperatelytryingtomakeittothe

escape

71podbeforethewholeshipexplodesItseemslikehardlyany

Gothons

72areontheshipsoyourrunisclearofinterferenceYou

gettothe

73chamberwiththeescapepodsandnowneedtopickoneto

takeSomeof

74themcouldbedamagedbutyoudonthavetimeto

lookTheres5pods

75whichonedoyoutake

76)

77

78

79the_end_winner=Room(TheEnd

80

81Youjumpintopod2andhittheejectbuttonThepodeasily

slidesout

82intospaceheadingtotheplanetbelowAsitfliestothe

planetyou

83lookbackandseeyourshipimplodethenexplodelikeabright

star

84takingouttheGothonshipatthesametimeYouwon

85)

86

87

88the_end_loser=Room(TheEnd

89

90YoujumpintoarandompodandhittheejectbuttonThepod

escapes

91outintothevoidofspacethenimplodesasthehull

rupturescrushing

92yourbodyintojamjelly

93

94)

95

96escape_podadd_paths(

972the_end_winner

98the_end_loser

99)

100

101generic_death=Room(deathYoudied)

102

103the_bridgeadd_paths(

104throwthebombgeneric_death

105slowlyplacethebombescape_pod

106)

107

108laser_weapon_armoryadd_paths(

1090132the_bridge

110generic_death

111)

112

113central_corridoradd_paths(

114shootgeneric_death

115dodgegeneric_death

116tellajokelaser_weapon_armory

117)

118

119START=central_corridor

120

121defload_room(name)

122

123Thereisapotentialsecurityproblemhere

124WhogetstosetnameCanthatexposeavariable

125

126returnglobals()get(name)

127

128defname_room(room)

129

130SamepossiblesecurityproblemCanyoutrustroom

131Whatsabettersolutionthanthisglobalslookup

132

133forkeyvalueinglobals()items()

134ifvalue==room

135returnkeyYoursquollnoticethatthereareacouple

ofproblemswithourRoomclassandthismap1Wehavetoputthe

textthatwasintheif-elseclausesthatgotprintedbeforeentering

aroomaspartofeachroomThismeansyoucanrsquotshufflethe

planispherearoundwhichwouldbeniceYoursquollbefixingthatupin

thisexercise

2TherearepartsintheoriginalgamewherewerancodethatdeterminedthingslikethebombrsquoskeypadcodeortherightpodInthisgamewejustpicksomedefaultsandgowithitbutlateryoursquollbegivenStudyDrillstomakethisworkagain

3Irsquovejustmadeageneric_deathendingforallofthebaddecisionswhichyoursquollhavetofinishformeYoursquollneedtogobackthroughandaddinalltheoriginalendingsandmakesuretheywork

4Irsquovegotanewkindoftransitionlabeledthatwillbeusedforaldquocatch-allrdquoactionintheengine

Onceyoursquovegotthatbasicallywrittenoutherersquosthenewautomatedtesttestsplanisphere_testpythatyoushouldhavetogetyourselfstartedClickheretoviewcodeimage

planisphere_testspy

1fromnosetoolsimport

2fromgothonwebplanisphereimport

3

4deftest_room()

5gold=Room(GoldRoom

6Thisroomhasgoldinityoucangrab

Theresa

7doortothenorth)

8assert_equal(goldnameGoldRoom)

9assert_equal(goldpaths)

10

11deftest_room_paths()

12center=Room(CenterTestroominthecenter)

13north=Room(NorthTestroominthenorth)

14south=Room(SouthTestroominthesouth)

15

16centeradd_paths(northnorthsouthsouth)

17assert_equal(centergo(north)north)

18assert_equal(centergo(south)south)

19

20deftest_map()

21start=Room(StartYoucangowestanddownahole)

22west=Room(TreesTherearetreeshereyoucango

east)

23down=Room(DungeonItsdarkdownhereyoucango

up)

24

25startadd_paths(westwestdowndown)

26westadd_paths(eaststart)

27downadd_paths(upstart)

28

29assert_equal(startgo(west)west)

30assert_equal(startgo(west)go(east)start)

31assert_equal(startgo(down)go(up)start)

32

33deftest_gothon_game_map()

34start_room=load_room(START)

35assert_equal(start_roomgo(shoot)generic_death)

36assert_equal(start_roomgo(dodge)generic_death)

37

38room=start_roomgo(tellajoke)

39assert_equal(roomlaser_weapon_armory)Yourtaskinthis

partoftheexerciseistocompletethemapandmaketheautomated

testcompletelyvalidatethewholemapThisincludesfixingallthe

generic_deathobjectstoberealendingsMakesurethisworksreally

wellandthatyourtestisascompleteaspossiblebecausewersquollbe

changingthismaplaterandyoursquollusetheteststomakesureit

keepsworking

CreatinganEngineYoushouldhaveyourgamemapworkingandagoodunittestforitInowwantyoutomakeasimplelittlegameenginethatwillruntheroomscollectinputfromtheplayerandkeeptrackofwhereaplayerisinthegameWersquollbeusingthesessionsyoujustlearnedtomakeasimplegameenginethatwilldothefollowing

1Startanewgamefornewusers2Presenttheroomtotheuser3Takeinputfromtheuser4Runuserinputthroughthegame5Displaytheresultsandkeepgoinguntiltheuserdies

Todothisyoursquoregoingtotakethetrustyapppyyoursquovebeenhackingonandcreateafullyworkingsession-basedgameengineThecatchisIrsquomgoingtomakeaverysimpleonewithbasicHTMLfilesanditrsquollbeuptoyoutocompleteitHerersquosthebaseengineClickheretoviewcodeimage

apppy

1fromflaskimportFlasksessionredirecturl_forescape

request

2fromflaskimportrender_template

3fromgothonwebimportplanisphere

4

5app=Flask(__name__)

6

7approute()

8defindex()

9thisisusedtosetupthesessionwithstartingvalues

10session[room_name]=planisphereSTART

11returnredirect(url_for(game))

12

13approute(gamemethods=[GETPOST])

14defgame()

15room_name=sessionget(room_name)

16

17ifrequestmethod==GET

18ifroom_name

19room=planisphereload_room(room_name)

20returnrender_template(show_roomhtmlroom=room)

21else

22whyisthereheredoyouneedit

23returnrender_template(you_diedhtml)

24else

25action=requestformget(action)

26

27ifroom_nameandaction

28room=planisphereload_room(room_name)

29next_room=roomgo(action)

30

31ifnotnext_room

32session[room_name]=

planispherename_room(room)

33else

34session[room_name]=

planispherename_room(next_room)

35

36returnredirect(url_for(game))

37

38

39YOUSHOULDCHANGETHISIFYOUPUTONTHEINTERNET

40appsecret_key=A0Zr98j3yXR~XHHjmN]LWXRT

41

42if__name__==__main__

43apprun()Thereareevenmorenewthingsinthisscript

butamazinglyitrsquosanentireweb-basedgameengineinasmallfile

BeforeyourunapppyyouneedtochangeyourPYTHONPATHenvironment

variableDonrsquotknowwhatthatisIknowitrsquoskindofdumbbutyou

havetolearnwhatthisistorunevenbasicPythonprogramsthatrsquos

howPythonpeoplelikethings

InyourTerminaltypeClickheretoviewcodeimageexportPYTHONPATH=$PYTHONPATH

OnWindowsPowerShelldoClickheretoviewcodeimage$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

YoushouldonlyhavetodoitoncepershellsessionbutifyougetanimporterrorthenyouprobablyneedtodothisoryoudiditwrongYoushouldnextdeletetemplateshello_formhtmlandtemplatesindexhtmlandcreatethetwotemplatesmentionedintheprecedingcodeHerersquosaverysimpletemplatesshow_roomhtmlClickheretoviewcodeimage

show_roomhtml

extendslayouthtml

blockcontent

lth1gtroomnamelth1gt

ltpregt

roomdescription

ltpregt

ifroomnamein[deathTheEnd]

ltpgtltahref=gtPlayAgainltagtltpgt

else

ltpgt

ltformaction=gamemethod=POSTgt

-ltinputtype=textname=actiongtltinputtype=SUBMITgt

ltformgt

ltpgt

endif

endblock

ThatisthetemplatetoshowaroomasyoutravelthroughthegameNextyouneedonetotellsomeonetheydiedinthecasethattheygottotheendofthemaponaccidentwhichistemplatesyou_diedhtmlClickheretoviewcodeimage

you_diedhtml

lth1gtYouDiedlth1gt

ltpgtLookslikeyoubitthedustltpgt

ltpgtltahref=gtPlayAgainltagtltpgtWiththoseinplaceyoushouldnow

beabletodothefollowing1Getthetesttestsapp_testspy

workingagainsothatyouaretestingthegameYouwonrsquotbeableto

domuchmorethanafewclicksinthegamebecauseofsessionsbut

youshouldbeabletodosomebasics

2Runthepython36apppyscriptandtestoutthegameYoushouldbeabletorefreshandfixthegamelikenormalYoushouldalsobeabletoworkwiththegameHTMLandengineuntilitdoesallthethingsyouwantittodo

YourFinalExamDoyoufeellikethiswasahugeamountofinformationthrownatyouallatonceGoodIwantyoutohavesomethingtotinkerwithwhileyoubuildyourskillsTocompletethisexerciseIrsquomgoingtogiveyouafinalsetoftasksforyoutocompleteonyourownYoursquollnoticethatwhatyoursquovewrittensofarisnrsquotverywellbuiltitisjustafirstversionofthecodeYourjobnowistomakethegamemorecompletebydoingthesethings

1FixallthebugsImentioninthecodeandanythatIdidnrsquotmentionIfyoufindnewbugsletmeknow

2Improvealloftheautomatedtestssothatyoutestmoreoftheapplicationandgettoapointwhereyouuseatestratherthanyourbrowsertochecktheapplicationwhileyouwork

3MaketheHTMLlookbetter4Researchloginsandcreateasignupsystemfortheapplicationsopeoplecanhaveloginsandhighscores

5Completethegamemapmakingitaslargeandfeature-completeaspossible

6Givepeoplealdquohelprdquosystemthatletsthemaskwhattheycandoateachroominthegame

7Addanyotherfeaturesyoucanthinkoftothegame8CreateseveralldquomapsrdquoandletpeoplechooseagametheywanttorunYourapppyengineshouldbeabletorunanymapofroomsyougiveitsoyoucansupportmultiplegames

9FinallyusewhatyoulearnedinExercises48and49tocreateabetterinputprocessorYouhavemostofthecodenecessaryyoujustneedtoimprovethegrammarandhookituptoyourinputformandtheGameEngine

Goodluck

Goodluck

CommonStudentQuestionsIrsquomusingsessionsinmygameandIcanrsquottestitwithnosetestsReadtheFlaskTestingDocumentationaboutldquoOtherTestingTricksrdquo(httpflaskpocooorgdocs012testingother-testing-tricks)forinformationoncreatingfakesessionsinsideyourtests

IgetanImportErrorItcouldbeoneormoreofthesewrongdirectorywrongPythonversionPYTHONPATHnotsetno__init__pyfileandorspellingmistakeinimport

NextSteps

YoursquorenotaprogrammerquiteyetIliketothinkofthisbookasgivingyouyourldquoprogrammingblackbeltrdquoYouknowenoughtostartanotherbookonprogrammingandhandleitjustfineThisbookshouldhavegivenyouthementaltoolsandattitudeyouneedtogothroughmostPythonbooksandactuallylearnsomethingItmightevenmakeiteasyIrecommendyoucheckoutsomeoftheseprojectsandtrytobuildsomethingwiththem

bullLearnRubyTheHardWay(httpslearnrubythehardwayorg)YouwilllearnevenmoreaboutprogrammingasyoulearnmoreprogramminglanguagessotrylearningRubytoo

bullTheDjangoTutorial(httpsdocsdjangoprojectcomen111intro)BuildawebapplicationwiththeDjangowebframework

bullSciPy(httpswwwscipyorg)Checkthisoutifyoursquoreintosciencemathandengineering

bullPyGame(httpwwwpygameorg)MakeagamewithgraphicsandsoundbullPandas(httppandaspydataorg)Usethisfordoingdatamanipulationandanalysis

bullNaturalLanguageToolkit(httpwwwnltkorg)Usethisforanalyzingwrittentextandwritingthingslikespamfiltersandchatbots

bullTensorFlow(httpswwwtensorfloworg)Usethisformachinelearningandvisualization

bullRequests(httpdocspython-requestsorg)LearntheclientsideofHTTPandtheweb

bullScraPy(httpsscrapyorg)Tryscrapingsomewebsitestogetinformationoffthem

bullKivy(httpskivyorg)Createuserinterfacesondesktopsandmobileplatforms

bullLearnCTheHardWay(httpslearncodethehardwayorg)AfteryoursquorefamiliarwithPythontrylearningCandalgorithmswithmyotherbookTakeitslowCisdifferentbutaverygoodthingtolearn

PickoneoftheprecedingresourcesandgothroughanytutorialsanddocumentationtheyhaveAsyougothroughdocumentationwithcodeinittype

inallofthecodeandmakeitworkThatrsquoshowIdoitThatrsquoshoweveryprogrammerdoesitReadingprogrammingdocumentationisnotenoughtolearnityouhavetodoitAfteryougetthroughthetutorialandanyotherdocumentationtheyhavemakesomethingAnythingwilldoevensomethingsomeoneelsehasalreadywrittenJustmakesomethingJustunderstandanythingyouwritewillprobablysuckThatrsquosalrightthoughIsuckateveryprogramminglanguageatfirstNobodywritespureperfectgoldwhentheyrsquoreabeginnerandanyonewhotellsyoutheydidisahugeliar

HowtoLearnAnyProgrammingLanguageIrsquomgoingtoteachyouhowtolearnmostoftheprogramminglanguagesyoumaywanttolearninthefutureTheorganizationofthisbookisbasedonhowIandmanyotherprogrammerslearnnewlanguagesTheprocessthatIusuallyfollowisasfollows

1Getabookorsomeintroductorytextaboutthelanguage2Gothroughthebookandtypeinallofthecodemakingallofitrun3Readthebookasyouworkonthecodetakingnotes4Usethelanguagetoimplementasmallsetofprogramsyouarefamiliarwithinanotherlanguage

5ReadotherpeoplersquoscodeinthelanguageandtrytocopytheirpatternsInthisbookIforcedyoutogothroughthisprocessveryslowlyandinsmallchunksOtherbooksarenrsquotorganizedthesamewayandthismeansyouhavetoextrapolatehowIrsquovemadeyoudothistohowtheircontentisorganizedThebestwaytodothisistoreadthebooklightlyandmakealistofallthemajorcodesectionsTurnthislistintoasetofexercisesbasedonthechaptersandthensimplydotheminorderoneatatimeTheprecedingprocessalsoworksfornewtechnologiesassumingtheyhavebooksyoucanreadForanythingwithoutbooksyoudotheaboveprocessbutuseonlinedocumentationorsourcecodeasyourinitialintroductionEachnewlanguageyoulearnmakesyouabetterprogrammerandasyoulearnmorelanguagestheybecomeeasiertolearnByyourthirdorfourthlanguageyoushouldbeabletopickupsimilarlanguagesinaweekwithstrangerlanguagestakinglongerNowthatyouknowPythonyoucouldpotentiallylearnRubyandJavaScriptfairlyquicklybycomparisonThisissimplybecausemanylanguagessharesimilarconceptsandonceyoulearntheconceptsinonelanguagetheyworkinothersThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbea

ThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbeastupidtouristAstupidtouristissomeonewhogoestoanothercountryandthencomplainsthatthefoodisnrsquotlikethefoodathome(ldquoWhycanrsquotIgetagoodburgerinthisstupidcountryrdquo)WhenyoursquorelearninganewlanguageassumethatwhatitdoesisnrsquotstupiditrsquosjustdifferentandembraceitsoyoucanlearnitAfteryoulearnalanguagethoughdonrsquotbeaslavetothatlanguagersquoswayofdoingthingsSometimesthepeoplewhousealanguageactuallydosomeveryidioticthingsfornootherreasonthanldquothatrsquoshowwersquovealwaysdoneitrdquoIfyoulikeyourstylebetterandyouknowhoweveryoneelsedoesitthenfeelfreetobreaktheirrulesifitimprovesthingsIreallyenjoylearningnewprogramminglanguagesIthinkofmyselfasaldquoprogrammeranthropologistrdquoandthinkoflanguagesaslittleinsightsaboutthegroupofprogrammerswhousethemIrsquomlearningalanguagetheyallusetotalktoeachotherthroughcomputersandIfindthisfascinatingThenagainIrsquomkindofaweirdguysojustlearnprogramminglanguagesbecauseyouwanttoEnjoyThisisreallyfunstuff

AdvicefromanOldProgrammer

YoursquovefinishedthisbookandhavedecidedtocontinuewithprogrammingMaybeitwillbeacareerforyouormaybeitwillbeahobbyYoursquollneedsomeadvicetomakesureyoucontinueontherightpathandgetthemostenjoymentoutofyournewlychosenactivityIrsquovebeenprogrammingforaverylongtimeSolongthatitrsquosincrediblyboringtomeAtthetimethatIwrotethisbookIknewabout20programminglanguagesandcouldlearnnewonesinaboutadaytoaweekdependingonhowweirdtheywereEventuallythoughthisjustbecameboringandcouldnrsquotholdmyinterestanymoreThisdoesnrsquotmeanIthinkprogrammingisboringorthatyouwillthinkitrsquosboringonlythatIfindituninterestingatthispointinmyjourneyWhatIdiscoveredafterthisjourneyoflearningisthatitrsquosnotthelanguagesthatmatterbutwhatyoudowiththemActuallyIalwaysknewthatbutIrsquodgetdistractedbythelanguagesandforgetitperiodicallyNowIneverforgetitandneithershouldyouWhichprogramminglanguageyoulearnandusedoesnrsquotmatterDonotgetsuckedintothereligionsurroundingprogramminglanguagesasthatwillonlyblindyoutotheirtruepurposeofbeingyourtoolfordoinginterestingthingsProgrammingasanintellectualactivityistheonlyartformthatallowsyoutocreateinteractiveartYoucancreateprojectsthatotherpeoplecanplaywithandyoucantalktothemindirectlyNootherartformisquitethisinteractiveMoviesflowtotheaudienceinonedirectionPaintingsdonotmoveCodegoesbothwaysProgrammingasaprofessionisonlymoderatelyinterestingItcanbeagoodjobbutyoucouldmakeaboutthesamemoneyandbehappierrunningafastfoodjointYoursquoremuchbetteroffusingcodeasyoursecretweaponinanotherprofessionPeoplewhocancodeintheworldoftechnologycompaniesareadimeadozenandgetnorespectPeoplewhocancodeinbiologymedicinegovernmentsociologyphysicshistoryandmathematicsarerespectedandcandoamazingthingstoadvancethosedisciplinesOfcourseallofthisadviceispointlessIfyoulikedlearningtowritesoftwarewiththisbookyoushouldtrytouseittoimproveyourlifeanywayyoucanGooutandexplorethisweirdwonderfulnewintellectualpursuitthatbarelyanyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhile

anyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhileyoucanFinallyIrsquollsaythatlearningtocreatesoftwarechangesyouandmakesyoudifferentNotbetterorworsejustdifferentYoumayfindthatpeopletreatyouharshlybecauseyoucancreatesoftwaremaybeusingwordslikeldquonerdrdquoMaybeyoursquollfindthatbecauseyoucandissecttheirlogictheyhatearguingwithyouYoumayevenfindthatsimplyknowinghowacomputerworksmakesyouannoyingandweirdtothemTothisIhavejustonepieceofadvicetheycangotohellTheworldneedsmoreweirdpeoplewhoknowhowthingsworkandwholovetofigureitalloutWhentheytreatyoulikethisjustrememberthatthisisyourjourneynottheirsBeingdifferentisnotacrimeandpeoplewhotellyouitisarejustjealousthatyoursquovepickedupaskilltheyneverintheirwildestdreamscouldacquireYoucancodeTheycannotThatisprettydamncool

AppendixCommandLineCrashCourse

ThisappendixisasuperfastcourseinusingthecommandlineItisintendedtobedonerapidlyinaboutadayortwoandnotmeanttoteachyouadvancedshellusage

IntroductionShutUpandShellThisappendixisacrashcourseinusingthecommandlinetomakeyourcomputerperformtasksAsacrashcourseitrsquosnotasdetailedorextensiveasmyotherbooksItissimplydesignedtogetyoubarelycapableenoughtostartusingyourcomputerlikearealprogrammerdoesWhenyoursquoredonewiththisappendixyouwillbeabletogivemostofthebasiccommandsthateveryshellusertoucheseverydayYoursquollunderstandthebasicsofdirectoriesandafewotherconceptsTheonlypieceofadviceIamgoingtogiveyouisthis

ShutupandtypeallofthisinSorrytobemeanbutthatrsquoswhatyouhavetodoIfyouhaveanirrationalfearofthecommandlinetheonlywaytoconqueranirrationalfearistojustshutupandfightthroughitYouarenotgoingtodestroyyourcomputerYouarenotgoingtobethrownintosomejailatthebottomofMicrosoftrsquosRedmondcampusYourfriendswonrsquotlaughatyouforbeinganerdSimplyignoreanystupidweirdreasonsyouhaveforfearingthecommandlineWhyBecauseifyouwanttolearntocodethenyoumustlearnthisProgramminglanguagesareadvancedwaystocontrolyourcomputerwithlanguageThecommandlineisthebabybrotherofprogramminglanguagesLearningthecommandlineteachesyoutocontrolthecomputerusinglanguageOnceyougetpastthatyoucanthenmoveontowritingcodeandfeelinglikeyouactuallyownthehunkofmetalyoujustbought

HowtoUseThisAppendixThebestwaytousethisappendixistodothefollowing

bullGetyourselfasmallpapernotebookandapenbullStartatthebeginningoftheappendixanddoeachexerciseexactlyasyoursquoretold

bullWhenyoureadsomethingthatdoesnrsquotmakesenseorthatyoudonrsquotunderstandwriteitdowninyournotebookLeavealittlespacesoyoucanwriteananswer

bullAfteryoufinishanexercisegobackthroughyournotebookandreviewthequestionsyouhaveTrytoanswerthembysearchingonlineandaskingfriendswhomightknowtheanswerEmailmeathelplearncodethehardwayorgandIrsquollhelpyoutoo

JustkeepgoingthroughthisprocessofdoinganexercisewritingdownquestionsyouhavethengoingbackthroughandansweringthequestionsyoucanBythetimeyoursquoredoneyoursquollactuallyknowalotmorethanyouthinkaboutusingthecommandline

YouWillBeMemorizingThingsIrsquomwarningyouaheadoftimethatIrsquomgoingtomakeyoumemorizethingsrightawayThisisthequickestwaytogetyoucapableatsomethingbutforsomepeoplememorizationispainfulJustfightthroughitanddoitanywayMemorizationisanimportantskillinlearningthingssoyoushouldgetoveryourfearofitHerersquoshowyoumemorizethings

bullTellyourselfyouwilldoitDonrsquottrytofindtricksoreasywaysoutofitjustsitdownanddoit

bullWritewhatyouwanttomemorizeonsomeindexcardsPutonehalfofwhatyouneedtolearnononesidethenanotherhalfontheotherside

bullEverydayforabout15to30minutesdrillyourselfontheindexcardstryingtorecalleachonePutanycardsyoudonrsquotgetrightintoadifferentpilejustdrillthosecardsuntilyougetboredthentrythewholedeckandseeifyouimprove

bullBeforeyougotobeddrilljustthecardsyougotwrongforabout5minutesthengotosleep

ThereareothertechniqueslikeyoucanwritewhatyouneedtolearnonasheetofpaperlaminateitthenstickittothewallofyourshowerWhileyoursquorebathingdrilltheknowledgewithoutlookingandwhenyougetstuckglanceatittorefreshyourmemoryIfyoudothiseverydayyoushouldbeabletomemorizemostthingsItellyoutomemorizeinaboutaweektoamonthOnceyoudonearlyeverythingelsebecomeseasierandintuitivewhichisthepurposeofmemorizationItrsquosnottoteachyouabstractconceptsbutrathertoingrainthebasicssothattheyareintuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthese

intuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthesebasicstheystopbeingspeedbumpspreventingyoufromlearningmoreadvancedabstractconcepts

TheSetupInthisappendixyouwillbeinstructedtodothreethings

bullDosomethingsinyourshell(commandlineTerminalPowerShell)bullLearnaboutwhatyoujustdidbullDomoreonyourown

ForthisfirstexerciseyoursquollbeexpectedtogetyourTerminalopenandworkingsothatyoucandotherestoftheappendix

DoThisGetyourTerminalshellorPowerShellworkingsoyoucanaccessitquicklyandknowthatitworksmacOS

FormacOSyoursquollneedtodothisbullHolddownthecommandkeyandhitthespacebarbullAsearchbarwillpopupbullTypeTerminalbullClickontheTerminalapplicationthatlookskindoflikeablackboxbullThiswillopenTerminalbullYoucannowgotoyourdockandCTRL-clicktopullupthemenuthenselectOptionsrarrKeepIndock

NowyouhaveyourTerminalopenanditrsquosinyourdocksoyoucangettoitLinux

IrsquomassumingthatifyouhaveLinuxthenyoualreadyknowhowtogetatyourTerminalLookthroughthemenuforyourwindowmanagerforanythingnamedldquoShellrdquoorldquoTerminalrdquoWindows

OnWindowswersquoregoingtousePowerShellPeopleusedtoworkwithaprogramcalledcmdexebutitrsquosnotnearlyasusableasPowerShellIfyouhaveWindows7orlaterdothis

bullClickStartbullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquo

bullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquobullHitEnter

IfyoudonrsquothaveWindows7youshouldseriouslyconsiderupgradingIfyoustillinsistonnotupgradingthenyoucantryinstallingPowerShellfromMicrosoftrsquosdownloadcenterSearchonlinetofindldquopowershelldownloadsrdquoforyourversionofWindowsYouareonyourownthoughsinceIdonrsquothaveWindowsXPbuthopefullythePowerShellexperienceisthesame

YouLearnedThisYoulearnedhowtogetyourTerminalopensoyoucandotherestofthisappendix

WarningIfyouhavethatreallysmartfriendwhoalreadyknowsLinuxignoreherwhenshetellsyoutousesomethingotherthanBashIrsquomteachingyouBashThatrsquositShewillclaimthatzshwillgiveyou30moreIQpointsandwinyoumillionsinthestockmarketIgnoreherYourgoalistogetcapableenoughandatthislevelitdoesnrsquotmatterwhichshellyouuseThenextwarningisstayoffIRCorotherplaceswhereldquohackersrdquohangoutTheythinkitrsquosfunnytohandyoucommandsthatcandestroyyourcomputerThecommandrm-rfisaclassicthatyoumustnevertypeJustavoidthemIfyouneedhelpmakesureyougetitfromsomeoneyoutrustandnotfromrandomidiotsontheinternet

DoMoreThisexercisehasalargeldquodomorerdquopartTheotherexercisesarenotasinvolvedasthisonebutIrsquomhavingyouprimeyourbrainfortherestoftheappendixbydoingsomememorizationJusttrustmethiswillmakethingssilkysmoothlateronLinuxmacOS

TakethislistofcommandsandcreateindexcardswiththenamesontheleftononesideandthedefinitionsontheothersideDrillthemeverydaywhilecontinuingwiththelessonsinthisappendix

pwdprintworkingdirectoryhostnamemycomputerrsquosnetworkname

mkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectorymvmoveafileordirectorylesspagethroughafilecatprintthewholefilexargsexecuteargumentsfindfindfilesgrepfindthingsinsidefilesmanreadamanualpageaproposfindwhichmanualpageisappropriateenvlookatyourenvironmentechoprintsomeargumentsexportexportsetanewenvironmentvariableexitexittheshellsudoDANGERbecomesuperuserrootDANGER

Windows

IfyoursquoreusingWindowsthenherersquosyourlistofcommandspwdprintworkingdirectoryhostnamemycomputerrsquosnetworknamemkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectory

robocopyrobustcopymvmoveafileordirectorymorepagethroughafiletypeprintthewholefileforfilesrunacommandonlotsoffilesdir-rfindfilesselect-stringfindthingsinsidefileshelpreadamanualpagehelpctrfindwhatmanualpageisappropriateechoprintsomeargumentssetexportsetanewenvironmentvariableexitexittheshellrunasDANGERbecomesuperuserrootDANGER

DrilldrilldrillDrilluntilyoucansaythesephrasesrightawaywhenyouseethatwordThendrilltheinversesothatyoureadthephraseandknowwhatcommandwilldothatYoursquorebuildingyourvocabularybydoingthisbutdonrsquotspendsomuchtimeyougonutsandgetbored

PathsFoldersDirectories(pwd)Inthisexerciseyoulearnhowtoprintyourworkingdirectorywiththepwdcommand

DoThisIrsquomgoingtoteachyouhowtoreadtheseldquosessionsrdquothatIshowyouYoudonrsquothavetotypeeverythingIlistherejustsomeoftheparts

bullYoudonottypeinthe$(Unix)orlt(Windows)ThatrsquosjustmeshowingyoumysessionsoyoucanseewhatIgot

bullYoutypeinthestuffafter$orltthenhitEnterSoifIhave$pwdyoutypejustpwdandhitEnter

bullYoucanthenseewhatIhaveforoutputfollowedbyanother$orltpromptThatcontentistheoutputandyoushouldseethesameoutput

LetrsquosdoasimplefirstcommandsoyoucangetthehangofthisLinuxmacOS

Exercise2Session

$pwd

Userszedshaw

$

Windows

Exercise2WindowsSession

PSCUserszedgtpwd

Path

----

CUserszed

PSCUserszedlt

WarningInthisappendixIneedtosavespacesothatyoucanfocusontheimportantdetailsofthecommandsTodothisIrsquomgoingtostripoutthefirstpartoftheprompt(thePSCUserszedabove)andleavejustthelittlegtpartThismeansyourpromptwonrsquotlookexactlythesamebutdonrsquotworryaboutthatRememberthatfromnowonIrsquollonlyhavethegttotellyouthatrsquosthepromptIrsquomdoingthesamethingfortheUnixpromptsbutUnixpromptsaresovariedthatmostpeoplegetusedto$meaningldquojustthepromptrdquo

YouLearnedThisYourpromptwilllookdifferentfrommineYoumayhaveyourusernamebeforethe$andthenameofyourcomputerOnWindowsitwillprobablylookdifferenttooThekeyisthatyouseethefollowingpattern

bullTherersquosapromptbullYoutypeacommandthereInthiscaseitrsquospwdbullItprintedsomethingbullRepeat

Youjustlearnedwhatpwddoeswhichmeansldquoprintworkingdirectoryrdquo

WhatrsquosadirectoryItrsquosafolderFolderanddirectoryarethesamethingandtheyrsquoreusedinterchangeablyWhenyouopenyourfilebrowseronyourcomputertographicallyfindfilesyouarewalkingthroughfoldersThosefoldersaretheexactsamethingsastheseldquodirectoriesrdquowersquoregoingtoworkwith

DoMorebullTypepwd20timesandeachtimesayldquoprintworkingdirectoryrdquobullWritedownthepaththatthiscommandgivesyouFinditwithyourgraphicalfilebrowserofchoice

bullNoseriouslytypeit20timesandsayitoutloudSsshJustdoit

IfYouGetLostAsyougothroughtheseinstructionsyoumaygetlostYoumaynotknowwhereyouareorwhereafileisandhavenoideahowtocontinueTosolvethisproblemIamgoingtoteachyouthecommandstotypetostopbeinglostWheneveryougetlostitismostlikelybecauseyouweretypingcommandsandhavenoideawhereyoursquoveendedupWhatyoushoulddoistypepwdtoprintyourcurrentdirectoryThistellsyouwhereyouareThenextthingisyouneedtohaveawayofgettingbacktowhereyouaresafeyourhomeTodothistypecd~andyouarebackinyourhomeThismeansifyougetlostatanytimetype

pwd

cd~

ThefirstcommandpwdtellsyouwhereyouareThesecondcommandcd~takesyouhomesoyoucantryagain

DoThisRightnowfigureoutwhereyouareandthengohomeusingpwdandcd~Thiswillmakesureyouarealwaysintherightplace

YouLearnedThisHowtogetbacktoyourhomeifyouevergetlost

MakeaDirectory(mkdir)Inthisexerciseyoulearnhowtomakeanewdirectory(folder)usingthemkdircommand

DoThis

DoThisRememberYouneedtogohomefirstDoyourpwdthencd~beforedoingthisexerciseBeforeyoudoallexercisesinthisappendixalwaysgohomefirstLinuxmacOS

Clickheretoviewcodeimage

Exercise4Session

$pwd

$cd~

$mkdirtemp

$mkdirtempstuff

$mkdirtempstuffthings

$mkdir-ptempstuffthingsorangeapplepeargrape

$

Windows

Clickheretoviewcodeimage

Exercise4WindowsSession

gtpwd

gtcd~

gtmkdirtemp

DirectoryCUserszed

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMtemp

gtmkdirtempstuff

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMstuff

gtmkdirtempstuffthings

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtmkdirtempstuffthingsorangeapplepeargrape

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gt

ThisistheonlytimeIrsquolllistthepwdandcd~commandsTheyareexpectedintheexerciseseverytimeDothemallthetime

YouLearnedThisNowwegetintotypingmorethanonecommandTheseareallthedifferentwaysyoucanrunmkdirWhatdoesmkdirdoItmakesdirectoriesWhyareyouaskingthatYoushouldbedoingyourindexcardsandgettingyourcommandsmemorizedIfyoudonrsquotknowthatldquomkdirmakesdirectoriesrdquothenkeepworkingtheindexcardsWhatdoesitmeantomakeadirectoryYoumightcalldirectoriesldquofoldersrdquoTheyrsquorethesamethingAllyoudidaboveiscreatedirectoriesinsidedirectoriesinsideofmoredirectoriesThisiscalledaldquopathrdquoanditrsquosawayofsayingldquofirsttempthenstuffthenthingsandthatrsquoswhereIwantitrdquoItrsquosasetofdirectionstothecomputerofwhereyouwanttoputsomethinginthetreeoffolders(directories)thatmakeupyourcomputerrsquosharddisk

WarningInthisappendixIrsquomusingthe(slash)characterforallpathssincetheyworkthesameonallcomputersnowHoweverWindowsuserswillneedtoknowthatyoucanalsousethe(backslash)characterandotherWindowsuserswilltypicallyexpectthatattimes

DoMorebullTheconceptofaldquopathrdquomightconfuseyouatthispointDonrsquotworryWersquolldoalotmorewiththemandthenyoursquollgetit

bullMake20otherdirectoriesinsidethetempdirectoryinvariouslevelsGolookatthemwithagraphicalfilebrowser

bullMakeadirectorywithaspaceinthenamebyputtingquotesarounditmkdirIHaveFun

bullIfthetempdirectoryalreadyexiststhenyoursquollgetanerrorUsecdtochangetoaworkdirectorythatyoucancontrolandtryitthereOnWindowsDesktopisagoodplace

ChangeDirectory(cd)Inthisexerciseyoulearnhowtochangefromonedirectorytoanotherusingthecdcommand

DoThisIrsquomgoingtogiveyoutheinstructionsforthesesessionsonemoretime

bullYoudonottypeinthe$(Unix)orgt(Windows)bullYoutypeinthestuffafterthisthenhitEnterIfIhave$cdtempyoujusttypecdtempandhitEnter

bullTheoutputcomesafteryouhitEnterfollowedbyanother$orgtpromptbullAlwaysgohomefirstDopwdandthencd~soyougobacktoyourstartingpoint

LinuxmacOS

Clickheretoviewcodeimage

Exercise5Session

$cdtemp

$pwd

~temp

$cdstuff

$pwd

~tempstuff

$cdthings

$pwd

~tempstuffthings

$cdorange

$pwd

~tempstuffthingsorange

$cdapple

$pwd

~tempstuffthingsorangeapple

$cdpear

$pwd

~tempstuffthingsorangeapplepear

$cdgrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$cd

$pwd

~tempstuffthingsorangeapple

$cd

$cd

$pwd

~tempstuffthings

$cd

$pwd

~

$cdtempstuffthingsorangeapplepeargrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$pwd

~

$

Windows

Clickheretoviewcodeimage

Exercise5WindowsSession

gtcdtemp

gtpwd

Path

----

CUserszedtemp

gtcdstuff

gtpwd

Path

----

CUserszedtempstuff

gtcdthings

gtpwd

Path

----

CUserszedtempstuffthings

gtcdorange

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcdapple

gtpwd

Path

----

CUserszedtempstuffthingsorangeapple

gtcdpear

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepear

gtcdgrape

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepeargrape

gtcd

gtcd

gtcd

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcd

gtpwd

Path

----

CUserszedtempstuff

gtcd

gtcd

gtcdtempstuffthingsorangeapplepeargrape

gtcd

gtpwd

Path

----

CUserszed

gt

YouLearnedThisYoumadeallthesedirectoriesinthelastexerciseandnowyoursquorejustmovingaroundinsidethemwiththecdcommandInmysessionaboveIalsousepwdtocheckwhereIamsoremembernottotypetheoutputthatpwdprintsForexampleonline3yousee~tempbutthatrsquostheoutputofpwdfromthepromptaboveitDonottypethisinYoushouldalsoseehowIusethetomoveldquouprdquointhetreeandpath

DoMoreAveryimportantpartoflearningtousethecommandlineinterface(CLI)onacomputerwithagraphicaluserinterface(GUI)isfiguringouthowtheyworktogetherWhenIstartedusingcomputerstherewasnoGUIandyoudideverythingwiththeDOSprompt(theCLI)LaterwhencomputersbecamepowerfulenoughthateveryonecouldhavegraphicsitwassimpleformetomatchCLIdirectorieswithGUIwindowsandfoldersMostpeopletodayhoweverhavenocomprehensionoftheCLIpathsanddirectoriesInfactitrsquosverydifficulttoteachittothemandtheonlywaytolearnabouttheconnectionisforyoutoconstantlyworkwiththeCLIuntilonedayitclicksthatthingsyoudointheGUIwillshowupintheCLI

dayitclicksthatthingsyoudointheGUIwillshowupintheCLIThewayyoudothisisbyspendingsometimefindingdirectorieswithyourGUIfilebrowserthengoingtothemwithyourCLIThisiswhatyoursquolldonext

bullcdtotheappledirectorywithonecommandbullcdbacktotempwithonecommandbutnotfurtherabovethatbullFindouthowtocdtoyourldquohomedirectoryrdquowithonecommandbullcdtoyourDocumentsdirectorythenfinditwithyourGUIfilebrowser(FinderWindowsExploreretc)

bullcdtoyourDownloadsdirectorythenfinditwithyourfilebrowserbullFindanotherdirectorywithyourfilebrowserthencdtoitbullRememberwhenyouputquotesaroundadirectorywithspacesinitYoucandothatwithanycommandForexampleifyouhaveadirectoryIHaveFunthenyoucandocdIHaveFun

ListDirectory(ls)Inthisexerciseyoulearnhowtolistthecontentsofadirectorywiththelscommand

DoThisBeforeyoustartmakesureyoucdbacktothedirectoryabovetempIfyouhavenoideawhereyouareusepwdtofigureitoutandthenmovethereLinuxmacOS

Exercise6Session

$cdtemp

$ls

stuff

$cdstuff

$ls

things

$cdthings

$ls

orange

$cdorange

$ls

apple

$cdapple

$ls

pear

$cdpear

$ls

$cdgrape

$ls

$cd

$ls

grape

$cd

$ls

orange

$cd

$ls

stuff

$

Windows

Clickheretoviewcodeimage

Exercise6WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuff

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcdthings

gtls

DirectoryCUserszedtempstuffthings

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMorange

gtcdorange

gtls

DirectoryCUserszedtempstuffthingsorange

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMapple

gtcdapple

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcdpear

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcdgrape

gtls

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gt

YouLearnedThisThelscommandlistsoutthecontentsofthedirectoryyouarecurrentlyinYoucanseemeusecdtochangeintodifferentdirectoriesandthenlistwhatrsquosinthemsoIknowwhichdirectorytogotonextTherearealotofoptionsforthelscommandbutyoursquolllearnhowtogethelponthoselaterwhenwecoverthehelpcommand

DoMore

bullTypeeveryoneofthesecommandsinYouhavetoactuallytypethesetolearnthemJustreadingthemisnotgoodenoughIrsquollstopyellingnow

bullOnUnixtrythels-lRcommandwhileyoursquoreintempbullOnWindowsdothesamethingwithdir-RbullUsecdtogettootherdirectoriesonyourcomputerandthenuselstoseewhatrsquosinthem

bullUpdateyournotebookwithnewquestionsIknowyouprobablyhavesomebecauseIrsquomnotcoveringeverythingaboutthiscommand

bullRememberthatifyougetlostuselsandpwdtofigureoutwhereyouareandthengotowhereyouneedtobewithcd

RemoveDirectory(rmdir)Inthisexerciseyoulearnhowtoremoveanemptydirectory

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise7Session

$cdtemp

$ls

stuff

$cdstuffthingsorangeapplepeargrape

$cd

$rmdirgrape

$cd

$rmdirpear

$cd

$ls

apple

$rmdirapple

$cd

$ls

orange

$rmdirorange

$cd

$ls

things

$rmdirthings

$cd

$ls

stuff

$rmdirstuff

$pwd

~temp

$

WarningIfyoutrytodormdironmacOSanditrefusestoremovethedirectoryeventhoughyouarepositiveitrsquosemptythenthereisactuallyafileintherecalledDS_StoreInthatcasetyperm-rfltdirgtinstead(replaceltdirgtwiththedirectoryname)

Windows

Clickheretoviewcodeimage

Exercise7WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuffthingsorangeapplepeargrape

gtcd

gtrmdirgrape

gtcd

gtrmdirpear

gtcd

gtrmdirapple

gtcd

gtrmdirorange

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMthings

gtrmdirthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMstuff

gtrmdirstuff

gtpwd

Path

----

CUserszedtemp

gtcd

gt

YouLearnedThisIrsquomnowmixingupthecommandssomakesureyoutypethemexactlyandpayattentionEverytimeyoumakeamistakeitrsquosbecauseyouarenrsquotpayingattentionIfyoufindyourselfmakingmanymistakesthentakeabreakorjustquitforthedayYoursquovealwaysgottomorrowtotryagainInthisexampleyoursquolllearnhowtoremoveadirectoryItrsquoseasyYoujustgotothedirectoryrightaboveitthentypermdirltdirgtreplacingltdirgtwiththenameofthedirectorytoremove

DoMorebullMake20moredirectoriesandremovethemallbullMakeasinglepathofdirectoriesthatis10deepandremovethemoneatatimejustlikeIdidpreviously

bullIfyoutrytoremoveadirectorywithcontentsyouwillgetanerrorIrsquollshowyouhowtoremovethoseinlaterexercises

MovingAround(pushdpopd)InthisexerciseyoulearnhowtosaveyourcurrentlocationandgotoanewlocationwithpushdYouthenlearnhowtoreturntothesavedlocationwithpopd

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise8Session

$cdtemp

$mkdirilikeicecream

$pushdilikeicecream

~tempilikeicecream~temp

$popd

~temp

$pwd

~temp

$pushdilike

tempiliketemp

$pwd

~tempilike

$pushdicecream

~tempilikeicecreamtempiliketemp

$pwd

~tempilikeicecream

$popd

tempiliketemp

$pwd

~tempilike

$popd

~temp

$pushdilikeicecream

~tempilikeicecream~temp

$pushd

~temp~tempilikeicecream

$pwd

~temp

$pushd

~tempilikeicecream~temp

$pwd

~tempilikeicecream

$

Windows

Windows

Clickheretoviewcodeimage

Exercise8WindowsSession

gtcdtemp

gtmkdirilikeicecream

DirectoryCUserszedtempilike

ModeLastWriteTimeLengthName

---------------------------

d----122020111105AMicecream

gtpushdilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtemp

gtpushdilike

gtpwd

Path

----

CUserszedtempilike

gtpushdicecream

gtpwd

Path

----

CUserszedtempilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtempilike

gtpopd

gt

WarningInWindowsyounormallydonrsquotneedthe-poptionlikeyoudoinLinuxHoweverIbelievethisisamorerecentdevelopmentsoyoumayrunintoolderWindowsPowerShellversionsthatdorequirethe-pIfyouhavemoreinformationonthispleaseemailmeathelplearncodethehardwayorgsoIcansortoutwhethertomention-pforWindowsornot

YouLearnedThisYoursquoregettingintoprogrammerterritorywiththesecommandsbuttheyrsquoresohandyIhavetoteachthemtoyouThesecommandsletyoutemporarilygotoadifferentdirectoryandthencomebackeasilyswitchingbetweenthetwoThepushdcommandtakesyourcurrentdirectoryandldquopushesrdquoitintoalistforlaterthenitchangestoanotherdirectoryItrsquoslikesayingldquoSavewhereIamthengohererdquoThepopdcommandtakesthelastdirectoryyoupushedandldquopopsrdquoitofftakingyoubackthereFinallyonUnixpushdifyourunitbyitselfwithnoargumentsitwillswitchbetweenyourcurrentdirectoryandthelastoneyoupushedItrsquosaneasywaytoswitchbetweentwodirectoriesThisdoesnotworkinPowerShell

DoMorebullUsethesecommandstomovearounddirectoriesalloveryourcomputerbullRemovetheilikeicecreamdirectoriesandmakeyourownthenmovearoundinthem

bullExplaintoyourselftheoutputthatpushdandpopdwillprintoutforyouNoticehowitworkslikeastack

bullYoualreadyknowthisbutrememberthatmkdir-p(onLinuxmacOS)willmakeanentirepathevenifallthedirectoriesdonrsquotexistThatrsquoswhatIdidfirstforthisexercise

bullRememberthatWindowswillmakeafullpathanddoesnotneedthe-p

MakingEmptyFiles(touchNew-Item)Inthisexerciseyoulearnhowtomakeanemptyfileusingthetouch(New-ItemonWindows)command

DoThisLinuxmacOS

Exercise9Session

$cdtemp

$touchiamcooltxt

$ls

iamcooltxt

$

Windows

Clickheretoviewcodeimage

Exercise9WindowsSession

gtcdtemp

gtNew-Itemiamcooltxt-typefile

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12172011903AMiamcooltxt

gt

YouLearnedThisYoulearnedhowtomakeanemptyfileOnUnixtouchdoesthisanditalsochangesthetimesonthefileIrarelyuseitforanythingotherthanmakingemptyfilesOnWindowsyoudonrsquothavethiscommandsoyoulearnedhowtousetheNew-Itemcommandwhichdoesthesamethingbutcanalsomakenewdirectories

DoMorebullUnixMakeadirectorychangetoitandthenmakeafileinitThenchangeonelevelupandrunthermdircommandinthisdirectoryYoushouldgetanerrorTrytounderstandwhyyougotthiserror

bullWindowsDothesamethingbutyouwonrsquotgetanerrorYoursquollgetapromptaskingifyoureallywanttoremovethedirectory

CopyaFile(cp)Inthisexerciseyoulearnhowtocopyafilefromonelocationtoanotherwiththecpcommand

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise10Session

$cdtemp

$cpiamcooltxtneattxt

$ls

iamcooltxtneattxt

$cpneattxtawesometxt

$ls

awesometxtiamcooltxtneattxt

$cpawesometxtthefourthfiletxt

$ls

awesometxtiamcooltxtneattxtthefourthfiletxt

$mkdirsomething

$cpawesometxtsomething

$ls

awesometxtiamcooltxtneattxtsomethingthefourthfiletxt

$lssomething

awesometxt

$cp-rsomethingnewplace

$lsnewplace

awesometxt

$

Windows

Clickheretoviewcodeimage

Exercise10WindowsSession

gtcdtemp

gtcpiamcooltxtneattxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpneattxtawesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpawesometxtthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtmkdirsomething

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

gtcpawesometxtsomething

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtlssomething

DirectoryCUserszedtempsomething

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtcp-recursesomethingnewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gt

YouLearnedThisNowyoucancopyfilesItrsquossimpletojusttakeafileandcopyittoanewoneInthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectory

InthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectoryIrsquomgoingtotellyouasecretaboutprogrammersandsystemadministratorsnowTheyarelazyIrsquomlazyMyfriendsarelazyThatrsquoswhyweusecomputersWeliketomakecomputersdoboringthingsforusIntheexercisessofaryouhavebeentypingrepetitiveboringcommandssothatyoucanlearnthembutusuallyitrsquosnotlikethisUsuallyifyoufindyourselfdoingsomethingboringandrepetitivetherersquosprobablyaprogrammerwhohasfiguredouthowtomakeiteasierYoujustdonrsquotknowaboutityetTheotherthingaboutprogrammersistheyarenrsquotnearlyascleverasyouthinkIfyouoverthinkwhattotypethenyoursquollprobablygetitwrongInsteadtrytoimaginewhatthenameofacommandistoyouandtryitChancesarethatitrsquosanameorsomeabbreviationsimilartowhatyouthoughtitwasIfyoustillcanrsquotfigureitoutintuitivelythenaskaroundandsearchonlineHopefullyitrsquosnotsomethingreallystupidlikeROBOCOPY

DoMorebullUsethecp-rcommandtocopymoredirectorieswithfilesinthembullCopyafiletoyourhomedirectoryordesktopbullFindthesefilesinyourGUIandopentheminatexteditorbullNoticehowsometimesIputa(slash)attheendofadirectoryThatmakessurethefileisreallyadirectorysoifthedirectorydoesnrsquotexistIrsquollgetanerror

MovingaFile(mv)Inthisexerciseyoulearnhowtomoveafilefromonelocationtoanotherusingthemvcommand

DoThisLinuxmacOS

Exercise11Session

$cdtemp

$mvawesometxtuncooltxt

$ls

newplaceuncooltxt

$mvnewplaceoldplace

$ls

oldplaceuncooltxt

$mvoldplacenewplace

$ls

newplaceuncooltxt

$

Windows

Clickheretoviewcodeimage

Exercise11WindowsSession

gtcdtemp

gtmvawesometxtuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvnewplaceoldplace

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMoldplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvoldplacenewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gt

YouLearnedThisMovingfilesorratherrenamingthemItrsquoseasygivetheoldnameandthenewname

DoMoreMoveafileinthenewplacedirectorytoanotherdirectorythenmoveitback

ViewaFile(lessmore)TodothisexerciseyoursquoregoingtodosomeworkusingthecommandsyouknowsofarYoursquollalsoneedatexteditorthatcanmakeplaintext(txt)filesHerersquoswhatyoudo

bullOpenyourtexteditorandtypesomestuffintoanewfileOnmacOSthiscouldbeTextWranglerOnWindowsthismightbeNotepad++OnLinuxthiscouldbegeditAnyeditorwillwork

bullSavethatfiletoyourdesktopandnameittesttxtbullInyourshellusethecommandsyouknowtocopythisfiletoyourtempdirectorythatyoursquovebeenworkingwith

Onceyoursquovedonethatcompletethisexercise

Onceyoursquovedonethatcompletethisexercise

DoThisLinuxmacOS

Exercise12Session

$lesstesttxt

[displaysfilehere]

$

ThatrsquositTogetoutoflessjusttypeq(asinquit)Windows

Exercise12WindowsSession

gtmoretesttxt

[displaysfilehere]

gt

WarningIntheprecedingoutputIrsquomshowing[displaysfilehere]toldquoabbreviaterdquowhatthatprogramshowsIrsquolldothiswhenImeantosayldquoShowingyoutheoutputofthisprogramistoocomplexsojustinsertwhatyouseeonyourcomputerhereandpretendIdidshowittoyourdquoYourscreenwillnotactuallyshowthis

YouLearnedThisThisisonewaytolookatthecontentsofafileItrsquosusefulbecauseifthefilehasmanylinesitwillldquopagerdquosothatonlyonescreenfulatatimeisvisibleIntheDoMoresectionyoursquollplaywiththissomemore

DoMorebullOpenyourtextfileagainandrepeatedlycopy-pastethetextsothatitrsquosabout50ndash100lineslong

bullCopyittoyourtempdirectoryagainsoyoucanlookatitbullNowdotheexerciseagainbutthistimepagethroughitOnUnixyouuse

thespacebarandw(theletterw)togodownandupArrowkeysalsoworkOnWindowsjusthitthespacebartopagethrough

bullLookatsomeoftheemptyfilesyoucreatedtoobullThecpcommandwilloverwritefilesthatalreadyexistsobecarefulcopyingfilesaround

StreamaFile(cat)YoursquoregoingtodosomemoresetupforthisonesoyougetusedtomakingfilesinoneprogramandthenaccessingthemfromthecommandlineWiththesametexteditorfromthelastexercisecreateanotherfilenamedtest2txtbutthistimesaveitdirectlytoyourtempdirectory

DoThisLinuxmacOS

Exercise13Session

$lesstest2txt

[displaysfilehere]

$cattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

$cattesttxt

Hitherethisiscool

$

Windows

Exercise13WindowsSession

gtmoretest2txt

[displaysfilehere]

gtcattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

gtcattesttxt

Hitherethisiscool

gt

RememberthatwhenIsay[displaysfilehere]IrsquomabbreviatingtheoutputofthatcommandsoIdonrsquothavetoshowyouexactlyeverything

YouLearnedThisDoyoulikemypoemTotallygoingtowinaNobelAnywayyoualreadyknowthefirstcommandandIrsquomjusthavingyoucheckthatyourfileisthereThenyoucatthefiletothescreenThiscommandjustspewsthewholefiletothescreenwithnopagingorstoppingTodemonstratethatIhaveyoudothistotesttxtwhichshouldjustspewabunchoflinesfromthatexercise

DoMorebullMakeafewmoretextfilesandworkwithcatbullUnixTrycattesttxttest2txtandseewhatitdoesbullWindowsTrycattesttxttest2txtandseewhatitdoes

RemovingaFile(rm)Inthisexerciseyoulearnhowtoremove(delete)afileusingthermcommand

DoThisLinux

Clickheretoviewcodeimage

Exercise14Session

$cdtemp

$ls

uncooltxtiamcooltxtneattxtsomethingthefourthfiletxt

$rmuncooltxt

$ls

iamcooltxtneattxtsomethingthefourthfiletxt

$rmiamcooltxtneattxtthefourthfiletxt

$ls

something

$cp-rsomethingnewplace

$

$rmsomethingawesometxt

$rmdirsomething

$rm-rfnewplace

$ls

$

Windows

Clickheretoviewcodeimage

Exercise14WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtrmuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtrmiamcooltxt

gtrmneattxt

gtrmthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

gtcp-rsomethingnewplace

gtrmsomethingawesometxt

gtrmdirsomething

gtrm-rnewplace

gtls

gt

YouLearnedThisHerewecleanupthefilesfromthelastexerciseRememberwhenIhadyoutrytormdironadirectorywithsomethinginitWellthatfailedbecauseyoucanrsquotremoveadirectorywithfilesinitTodothatyouhavetoremovethefileorrecursivelydeleteallofitscontentsThatrsquoswhatyoudidattheendofthis

DoMorebullCleanupeverythingintempfromalltheexercisessofarbullWriteinyournotebooktobecarefulwhenrunningrecursiveremoveonfiles

ExitingYourTerminal(exit)DoThisLinuxmacOS

Exercise23Session

$exit

Windows

Exercise23WindowsSession

gtexit

YouLearnedThisYourfinalexerciseishowtoexitaTerminalAgainthisisveryeasybutIrsquomgoingtohaveyoudomore

DoMore

ForyourlastsetofexercisesIrsquomgoingtohaveyouusethehelpsystemtolookupasetofcommandsyoushouldresearchandlearnhowtouseonyourownHerersquosthelistforUnix

bullxargsbullsudobullchmodbullchown

ForWindowslookupthesethingsbullforfilesbullrunasbullattribbullicacls

Findoutwhattheseareplaywiththemandthenaddthemtoyourindexcards

CommandLineNextStepsYouhavecompletedthecrashcourseAtthispointyoushouldbeabarelycapableshelluserTherersquosawholehugelistoftricksandkeysequencesyoudonrsquotknowyetandIrsquomgoingtogiveyouafewfinalplacestogoresearchmore

UnixBashReferencesTheshellyoursquovebeenusingiscalledBashItrsquosnotthegreatestshellbutitrsquoseverywhereandhasalotoffeaturessoitrsquosagoodstartHerersquosashortlistoflinksaboutBashyoushouldgoread

BashCheatSheethttpslearncodethehardwayorgunixbash_cheat_sheetpdf(createdbyRaphaelandCClicensed)

ReferenceManualhttpwwwgnuorgsoftwarebashmanualbashrefhtml

PowerShellReferencesOnWindowstherersquosreallyonlyPowerShellHerersquosalistofusefullinksforyourelatedtoPowerShell

OwnerrsquosManualhttptechnetmicrosoftcomen-uslibraryee221100aspx

CheatSheethttpsdownloadmicrosoftcomdownload2122122F0B9-0EE6-4E6D-BFD6-F9DCD27C07F9WS12_QuickRef_Download_FilesPowerShell_LangRef_v3pdf

MasterPowerShellhttppowershellcomcsblogsebookdefaultaspx

Index

Symbols(colon)creatingfunctions61ndash62(dot)operator146ndash148193(double-quotes)avoidusingwithTrueFalse31createstrings26ndash27createstringswithsingle-quotesvs29escapinginsidestrings34ndash36promptandpass47

gt=(greater-than-equal)operator16ndash1797+=(incrementby)operator69ndash70105lt=(less-than-equal)operator16ndash1797-(minus)operator16ndash17=(notequal)operator97ndash98100ndash102(single-quotes)createstrings26ndash27createstringswithdouble-quotesvs29escapinginsidestrings34ndash36indicatingstrings57

(triple-single-quotes)36(triple-quotes)dedentfunction170ndash175errorswhenputtingspacesbetween33escapinginsidestrings3436

(slash)character16ndash17257(backslash)character33ndash34257(doublebacklash)character36_(underscore)character20ndash2162189+(plus)operator16ndash1754==(equal)operatorfunctionof21

practicingBooleanlogic100ndash102intruthtables98astruthterm97

=(single-equal)operator21(poundoroctothorpe)character1214ndash1517(percent)operator1617ndash18(asterisk)operator16ndash17[]leftandrightbracketslists112ndash114^(caret)characterviewoutput11charactersembeddedvariablesinstrings24ndash25lt(lessthan)operator16ndash17ltgt=(notequal)vs102gt(greaterthan)operator16ndash1791

AactivatescriptPowershell195Addressesweb225altered()functioninheritance180ndash183Alternativetexteditors6ndash7and

inBooleanlogic100ndash102astruthterm96ndash98

apppy

buildfirstwebsite217ndash221creategameengine239ndash241createHTMLforms228ndash229howformswork226ndash227writeautomatedtestsforforms231ndash232

app_testspyfile231241aproposcommand252args60ndash62Argumentscreatingfunctions6266argv

asargumentvariable42

promptingandpassingusing46ndash47readingandwritingfiles54readingfiles48ndash50unpacking42ndash44usinginput()vs44

Arrayslistsvs114ASCII(AmericanStandardCodeforInformationInterchange)80ndash81assert_equal()functionautomatedtesting201ndash203assert_raises()functionwritingtestexpectedtofail215asterisk()operator16ndash17Atomtexteditoralternativesto6ndash7Linuxsetup4ndash5macOSsetup2Windowssetup3ndash4workingwithfirstprogram9

Automatedtestsforforms232improving242overviewof200ndash203refactoringgothonwebgameusing238ndash239testfirstwith206ndash207

BBackslash()character33ndash34257Bashreferences283Big5encoding85bindirectoryskeletonprojectdirectory198Bits8182Blocksofcode106ndash110Booleanlogicmemorizingvslearning98practicing100ndash102rulesforif-statements126

Bottomupprocessesvstopdown169Brackets([])lists112ndash114Branchesandfunctions122ndash124Breakingfiles8592232Browsercreateenginetorungamein234ndash241gettinginputfromSeeInputgettingfrombrowserhowitaccessesinformation225ndash226

Bytesbreakingfiles85conventionsforencoding80ndash81defined78dissectingcode82ndash84dissectingoutput82

CC3algorithmsuper()function183Cardinalnumberslists120ndash121137caret(^)characterviewoutput11catcommandprintwholefile57252278ndash279cdcommandchangedirectorymacOSLinux251overviewof258ndash260Windows252

cd~command255CharactersencodingSeeStringsbytesandcharacterencodingsimportanceoflearningnamesof76fortruthterms96ndash97

Checklistcreatingfunction62ChildclassesSeeInheritancevscompositionClassesaddsconsistencytoprogram146asblueprintsfornewmini-modules149codeandtestinOOP167ndash169

designhierarchyinOOP166ndash167inheritancevscompositionSeeInheritancevscompositionobject-orientedphrasedrill152ndash153object-orientedreadingtest154ndash155object-orientedworddrill152researchingPython137similaritytomodules147ndash148styling189astemplatesmintingnewobjects186

CLI(commandlineinterface)usingonGUI261closecommandclosefile52ndash53Codeavoidhardcodingfilenames48blocksof106ndash107classestesting167ndash169createonelineof57findingerrorsin132inheritancevscompositionforreusable185OOPanalysisanddesign170ndash176parser211ndash214practicingEnglishto155reading132readingbackwardSeeReadingcodebackwardreadingphrases156refactoringforgothonwebgame234ndash239researchingpieceof78styling190testingotherprogrammerrsquos94typingintoTerminalPowerShell50

Colon()creatingfunctions61ndash62Colorsintexteditors12Command-linecrashcoursechangedirectory(cd)258ndash261copyfile(cp)272ndash275

exityourterminal(exit)282howtouseappendix248ndash249introduction248listdirectory(ls)261ndash265makedirectory(mkdir)255ndash257makeemptyfiles(touchNew-Item)271ndash272memorizingthings249movearound(pushdpopd)268ndash271movefile(mv)275ndash276pathsfoldersdirectories(pwd)253ndash255PowerShellreferences283removedirectory(rmdir)265ndash268removefile(rm)280ndash281setup249ndash253streamfile(cat)278ndash279UnixBashreferences283viewfile(lessmore)277ndash278

Commandlineinterface(CLI)usingonGUI261Commandsconvertingargumentstostrings44asfunctionsandmethods50learning44

Commentsaddingwhenreadingcode132creatingfunctionswith65ndash66designingdebuggingwith127functionsfileswith69gettinghelpwithdocumentation92is-ahas-arelationshipsusing159ndash160readingwritingfilesusing53usinginPython14ndash15variablenames21writinggood190writingwhenyoudonotunderstandcode29124

Composition

Compositiondefined152overviewof184ndash185whentouseinheritanceor185

Connectionsweb225ndash226Conventionsforencodingtext80ndash81Copyingfileswritingscriptfor56ndash58cpcopyfileordirectorymacOSLinux251overviewof272ndash275Windows252

curlcommandgeneraterequesttypes232

DDatastructuresdictionariesas140ndash144listsascommon136ndash137

Datatypeslistof129DBES(DecodeBytesEncodeStrings)dissectingcode83ndash84Debuggingdesigningand126ndash127fixingerrorsinfirstwebsite219refactoredcode241

Decisionsmaking108ndash110dedent()function-stylestrings170ndash175def(createfunction)branchesandfunctions122ndash124creategameengine239ndash241defined152filesworkingwithfunctions68ndash70functionscanreturnsomething72ndash74functionsworkingwithvariables90ndash93is-ahas-arelationships159ndash160overviewof60ndash62inreadingtest154ndash155

delkeyworddeletefromdictionary141Designinganddebugging126ndash127dict

howformswork227understandingdictionaries140ndash144

Dictionariesexampleof141ndash143functionsof143ndash144listsvs140ndash141modulessimilarto146ndash147storescenesbynamein175

diefunctionif-statementrules126dir-rfindfilesinWindows253DirectoriescausesofImportErrors209ldquoHelloWorldrdquowebapplication217LinuxmacOScommand-linefor251skeletonprojectSeeSkeletonprojectdirectoryWindowscommand-linefor252

DjangoTutorial244Documentationcheckoutprojectsbuildsomethingusing244gettinghelpwithcomments92writinggoodcomments190

Dot()operator146ndash148193Doublebacklash()36Double-quotesSee(double-quotes)

Eechoprintsomearguments252253Elementsaccessinglist120ndash121elif

branchesandfunctions122ndash124andelse107makingdecisions108ndash110

else

branchesandfunctions122ndash124andif-statement106ndash107makingdecisions108ndash110rulesforif-statements126

Encodingsbytescharacter80ndash85envcommandlookatyourenvironment252EqualoperatorSee==(equal)operatorErrormessagesbuildingfirstwebsite218ndash219EOFError155ImportErrorSeeImportErrorsNameError47ParserError211ndash214printing29forspacesbetweentriple-quotes33forspellingmistakes33ValueErrorSeeValueErrorsvariablenames21viewingoutputinfirstprogram11whenmakingscriptshorter58

Escapesequencesfordifferentcharactersinstrings34ndash35practicing87readingandwritingfiles54reviewing130supportedbyPython35

exceptkeywordexceptions206Exceptionshowtoraise211ndash214andnumbers206

existscommandcopyingfiles56ndash58exitcommandexitshell124252282exportcommandexportnewenvironmentvariable252

F

Ffcharacterembeddingvariablesinsidestrings24ndash25promptingandpassing46ndash47inreadline()70usingwithfunctions69

Falsekeywordavoidquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98

Featuresaddingtoscript42alsocalledmodules42ndash43

FileTransferProtocol(FTP)andURLs225Filenames48ndash50Filescopying56ndash58creating50andfunctions68ndash70LinuxmacOScommand-linefor251ndash252reading48ndash50readingandwriting52ndash54Windowscommand-linefor252ndash253

findcommandfiles252Firstprogramcreate8ndash12flaskframeworkcreatebasictemplatesforwebsite219ndash221creategameengine239ndash241fixerrors218ndash219ImportErrorafterinstalling222installingforfirstwebsite216makeldquoHelloWorldrdquowebapplication216ndash217testingtricksforcreatingfakesessions242webpyvs221

whatisgoingon218FLASK_DEBUGnotsafetoactivateonInternet219Flowcharts132FoldersSeeDirectoriesfooOOP152for-loops

buildinglistswith112ndash114rulesfor126whentouselists137while-loopsvs118

forOOP154ndash155forfiles253formatfunction30ndash31Formatstringsformatterformat()30oldstyle130ndash131overviewof24ndash25readingandwritingfiles54

format()syntaxformattingstrings26ndash2730Formsautomatedtestsfor232creatingHTML227ndash229howtheywork226ndash227

FTP(FileTransferProtocol)andURLs225Functionsaccessinginmodulewith(dot)operator146ndash147alsocalledmethodscommands50branchesand122ndash124canreturnsomething72ndash74createchecklistfor62andfiles68ndash70overviewof60ndash62practicing87ndash8890ndash93readingcode132

replicatingimplicitinheritance184ndash185styling189usingprintvsreturnin93andvariables64ndash6687ndash88viewingcalls137

GGamestartofyourwebcreatingengine239ndash241overviewof234refactoring234ndash239yourfinalexam241ndash242

GamesanalysisanddesignSeeObject-orientedanalysisanddesignmakingyour188ndash191

gothonwebprojectanalysisofsimplegameengine165ndash169codefor170ndash176creatinglayouttemplate234ndash239makingintofirstwebapplication217ndash221refactoringcodecreatingwebenginetorun234ndash241

Grammarmakingsentences211215Greater-than-equal(gt=)operator16ndash1797Greaterthan(gt)operator16ndash1791grepcommandfindthingsinsidefiles252GUI(graphicaluserinterface)usingCLIon261

HHardcodedfilenamesavoid48has-arelationships152158ndash162ldquoHelloWorldrdquowebapplicationcreatebasictemplates219ndash221fixingerrors218ndash219

Helpcreatesystemfor242

gettingmodule92helpcommandWindows253helpctrcommandWindows253Hierarchyclass166ndash169hostname

mycomputerrsquosnetworkname251252understandURLs225

HTMLcreatebasictemplatesforwebsite219ndash221createforms227ndash229creategameengine239ndash241improveappearanceof242research232understandresponse226

HTTPrequests218244researchHTTPREC232understandURLs225

IIDLEavoidusing1231if-elsetry-exceptvs209if-statements

branchesandfunctions122ndash124elseand106ndash107loopsandlists112ndash114makedecisions83ndash84108ndash110overviewof104ndash105readcode132rulesfor126

Implicitinheritancecombinewithothertypesofinheritance182compositionvs184ndash185overviewof178ndash179

import

addfeaturestoscript42copyfiles56ndash58filewithmodules146makeagameyourself188objectsassimilarto148ndash149

ImportErrorsafterinstallingflask222causesof209242createskeletonprojectdirectory199

Incrementby(+=)operator69ndash70105Indentation61ndash62106index()

creategameengine239ndash241createHTMLforms229howformswork227

indexGEThandler224Inheritanceavoidmultiple178183185object-orientedphrasedrill152object-orientedreadingtest154ndash155object-orientedworddrill152

Inheritancevscompositionalterbehaviorbeforeorafter180ndash181implicitinheritance179overrideexplicitly180overviewof178reasonforsuper()183threekindsofinheritancecombined182ndash183understandcomposition184ndash185understandinheritance178ndash179usinginheritancevscomposition185usingsuper()with__init__()183

__init__functioninitializingnewlycreatedemptyobject149

inis-ahas-arelationships159ndash162runningreliablyforparentclass162tryingnottodotoomuchin189usingselfwhenmakingfunctionsforclasses151usingsuper()in183

input()

askingquestions38ndash39enteringownvalues74parameterto(gt)124parametersunpackingvariables42ndash44promptingandpassing46ndash47promptingpeople40ndash41readingfiles48ndash50

Inputadvanceduserourgamelexicon204ndash206overviewof204testfirstchallenge206ndash207whatyoushouldtest207ndash209

Inputgettingfrombrowserbreakingit232creatingHTMLforms227ndash229creatinglayouttemplate229ndash230howformswork226ndash227howwebworks224ndash226writingautomatedtestsforforms232

ltinputgttags229ndash230Instance152ndash153Instantiation148ndash149Internetflaskdebuggermodenotsafeon219Internetresearchcheckoutprojectstrytobuildsomething244findthings5ndash6functionsandfiles69importstatement57

object-orientedprogramming137151pydoc40ndash41readingfiles49

int()functionconvertingcommandlineargumentstrings44IPaddressesandURLs225is-arelationships152158ndash162

JJinja2Documentationtemplatelanguage221

KKeywordslistof128ndash129Kivy244

LLayouttemplatecreate232LearnCTheHardWay244LearnRubyTheHardWay244len()function5658lesscommandviewfileinmacOSLinux252277ndash278Less-than-equal(lt=)operator16ndash1797Lessthan(lt)operator16ndash17LexiconcreatinggamemakesentencesSeeSentencesmakingoverviewof204ndash206testfirstchallenge206ndash207whatyoushouldtest207ndash209

Librariesdefined43LinuxmacOSalternativetexteditorsfor7getterminalopenandworking250ndash251projectskeletonsetup192ndash194setupexercise4ndash5

LinuxmacOScommand-linecatstreamfile278ndash279

cdchangedirectory258ndash259261cpcopyfileordirectory272274ndash275exitexitshell282lessviewfile277ndash278listofcommands251ndash252lslistdirectory262265mkdirmakedirectory256ndash257mvmovefileordirectory275277pushdpopd(movedirectory)268ndash271pwdprintworkingdirectory253ndash255rmstreamfile278ndash279rmdirremovedirectory266268

Listsaccesselementsof120ndash121buildusingfor-loops112ndash114doingthingsto134ndash138making2-D114processinglistsofthings78whentouse137

localhost

buildfirstwebsite218221webconnection225

Logicmemorizing96ndash98practicingBoolean100ndash102

Loginresearchingwebapplication242Lookuptablesdictionariesas144Loopsandlists112ndash114for-loopsSeefor-loopsmakinginfinite124rulesfor126ndash127while-loopsSeewhile-loops

lpthwvirtualenvironmentskeletonproject193195

lslistdirectorymacOSLinux251overviewof261ndash265Windows252

MmacOSSeeLinuxmacOSmainfunctiondissectingcode83manreadmanualpageinmacOSLinux252Mapclassgothonwebprojectcode171storingscenesbynameindictionary175

Mapsanalysisofsimplegameengine165completinggame242withdictionaries143ndash144

matchfunctionparsercode212Math16ndash1839Memorizationofcommandsusingindexcards251ndash253learningcommandline249oflogic96ndash98tipsfor96

Methodresolutionorder(MRO)super()183Methodsalsocalledfunctionsandcommands50functionsvs189

Minus(--)operator16ndash17mkdirmakedirectorymacOSLinux251overviewof255ndash257Windows252

Modifiersreadingandwritingfiles54ModulescausesofImportErrors209

gettinghelpfor92overviewof146ndash147replicatingimplicitinheritancein184ndash185usingclassesvs147ndash148

morecommandviewfileinWindows252278MRO(methodresolutionorder)super()183Multipleinheritanceavoid178183185mvcommandmovefileordirectorymacOSLinux251overviewof275ndash277Windows252

NNameErrormessage47Namescreatingfunction62189definemodules42ndash43filenames48ndash50importanceoflearningsymbol76variable20ndash2260ndash62

NaturalLanguageToolKit244Nestedstructureslistsas112rulesforif-statements126

new-itemcommandcreateemptyfilesinWindows271ndash272Noneforsomefunctions93nosetestscommandautomatedtests201ndash203automatedtestsforforms231createskeletonprojectdirectory197ndash199syntaxerror203

not

inBooleanlogic100ndash102intruthtables97ndash98

astruthterm97Notequal(=)operator97ndash98100ndash102Nounsobject-orientedprogramming164ndash167Numbersaccesselementsoflists120ndash121exceptionsand206indexlistsinto140ndash141inputtodomath39andmath16ndash18betweenrangeofnumbers110roundingfloatingpoint25

OObject-orientedanalysisanddesignSeealsoGamestartofyourwebanalysisofsimplegameengine165codeclassesandtesttorunthem167ndash169codeforldquoGothonsfromPlanetPercal25rdquo170ndash176createclasshierarchyobjectmapforconcepts166ndash167extractresearchkeyconcepts166overviewof164ndash165repeatandrefine169topdownvsbottomup169whatyoushouldsee176writeordrawaboutproblem165

Object-orientedprogramming(OOP)inheritancevscompositionSeeInheritancevscompositionPythonas146research137151speak152ndash156

Objectsclassesastemplatesthatmintnew186makesentenceswith210ndash211object-orientedphrasedrill152ndash153object-orientedworddrill152parsercode212ndash215

similartoimport148ndash149Octothorpe()character1214ndash1517opencommandreadingandwritingfiles52ndash54OperatorsfindingmorePythonequality102listof131ndash132math16ndash17variablename20ndash22

or

inBooleanlogic100ndash102intruthtables97ndash98astruthterm96

Ordermaintainwithlists137Ordinalnumberslists120ndash121Outputoffirstprogram10ndash11ldquoHelloWorldrdquowebapplication217

override()functioninheritance189

PPandas244Paragraphsif-statementrules126Parametersreadingandwritingfiles54ParentclassesSeeInheritancevscompositionParsercode211ndash214playingwith214ndash215

ParserErrorexception211ndash214Passingpromptingand46ndash47PEMDASacronymorderofmathoperations18Percent()operator1617ndash18Phrasedrillsobject-oriented152ndash156pip36(orjustpip)createskeletonprojectdirectory192ndash195198ndash199installflasktobuildfirstwebsite216

planispherepyfile234ndash238

planisphere_testspyfile238ndash239Plus(+)operator16ndash1754popdcommandpopdirectorymacOSLinux251overviewof268ndash271Windows252

Portswebconnections225POSTautomatedtestsforforms231creatingHTMLforms227ndash229

Pound()character1214ndash1517PowerShellcreategameengine240infirstprogram11ndash12references283typingcodeinto50Windows10setupfor3ndash4195250ndash251

print

debugwith127readcodeusing132whenfunctionsusereturnvs93

Printstringswithmorecomplicatedformatting30ndash31moreexercisesin28ndash2932ndash33usingescapesequences34ndash36variables24ndash25

print_a_linepassincurrentlinenumber68ndash69print_linefunctiondissectingcode83ndash84print_twofunctioncreatefunctions60ndash61Programminglanguagesadvicefromoldprogrammer246ndash247checkoutprojectstrytobuildsomething244howtolearnnew245learningcommandlineSeeCommand-linecrashcourse

Projectskeleton192ndash194Promptsidentifyinappendixexercises254andpassing46ndash47people40ndash41

Prototypelanguages186Pseudocodetestfirstusing207pushdcommandpushdirectorymacOSLinux251overviewof268ndash271Windows252

pwdcommandprintworkingdirectorymacOSLinux251overviewof253ndash255Windows252

pyfilespassingvariablestoscript42ndash44pydoccommandpromptpeople40ndash41PyGame244PYTHONPATHenvironmentvariable240

Qquit()functionreloadPythonafter92

Rraisekeywordexceptions211213ndash214range()functionloops114Rawbytes7982ndash84readcommandreadcontentsoffile52ndash54Readingcode132codeoutloud190files48ndash50andwritingfiles52ndash54

Readingcodebackwardcommentsandpoundcharacters14

defined88printing29reasonsfor15understandinghowto22

readline()function52ndash53687083Refactoringcode234ndash239render_template()function220ndash221requestargsforms227Requestswebgeneratingtypesofwithcurl232learnclientsideofHTTP244process224ndash225understand225

Responsesweb226return

functions72ndash74object-orientedreadingtest155whenfunctionsuseprintvs93

rmstreamfile280ndash281rmdircommandremovedirectorymacOSLinux251overviewof265ndash268Windows252

Roomclassautomatedtests201ndash203creategameengine239ndash241refactorcodeforgothonwebgame234ndash239

round()functionfloatingpointnumbers25Rulesforif-statements126forloops126ndash127whentouseinheritanceorcomposition185

runascommanddangerinwindows252

S

Scanninginputlexicontuples205209Scenes(rooms)analysisofsimplegameengine165ndash167codeclassesforsimplegame167ndash169gothonwebprojectcode170ndash176makinggameyourself188ndash191whatyoushouldsee176

SciPy244ScraPy244Scriptslinkingfunctionsto61makingdecisions107passingvariablesto42ndash44

SearchenginesfindingthingsonInternet5ndash6howtotype(octothorp)character15

seek()functiondefined52ndash53doesnotsetcurrentlineto070researchforfile69

select-stringcommandfindthingsinsideWindowsfiles253self

__init__function148151is-ahas-arelationshipsand159ndash160object-orientedlanguage152ndash155

Sentencesmakingbreakingup205exceptions211grammar211matchandpeek210ndash211overviewof210parsercode211ndash215whatyoushouldtest215

Servershowbrowsersaccessinformationon226

setcommandexportsetnewenvironmentvariableinWindows253Setupexercisealternativetexteditors6ndash7findingthingsonInternet5ndash6Linux4ndash5macOS2ndash3overviewof2warningsforbeginners6Windows3ndash4

setuppyfileskeletonprojectdirectory196198ndash199Single-equal(=)operator21Single-quotesSee(single-quotes)Skeletonprojectdirectoryautomatedtesting200ndash203creatingdirectorystructure195ndash197macOSLinuxsetup192ndash194overviewof192requiredquiz198testingsetup197ndash198using198Windows10setup194ndash195

skipkeywordparsercode213Slash()character16ndash17257Spaceaddingaroundoperatorsforeasierreading22makecodereadablewithvertical190

Spellingmistakeserrormessagesfor33Stopwordsparsercode213Stringsacrossmultiplelines34ndash36complicatedformattingof30ndash31convertcommandlineargumentsto44decodebytesandencode83ndash84embedvariablesinside24ndash25

exerciseinprinting28ndash29listofescapesequencesfor130listofoldstyleformatsfor130ndash131listsmixedwith135ndash136poundcharactersin15readwritefilesin54startnewlinein33andtext26ndash27understanding26asUTF-8encodedsequenceofcharacters82

Stringsbytesandcharacterencodingsbreakingit85dissectcode82ndash84dissectoutput82encodingsdeepdive84ndash85initialresearch78ndash80overviewof78switchesandconventions80ndash81

Stylingcode190functionsandclasses189

Subjectparsercode212ndash215ofsentences210ndash211

sudocommand252super()functioninheritance180ndash183Switches80ndash81Symbolsdatatypes129escapesequencesforstrings130keywords128ndash129learningnamesof76oldstylestringformats130ndash131operators131ndash132readingcode132

SyntaxErrormessageEOL58invalidsyntax1293promptingandpassing47pydoc41viewingoutputinfirstprogram11

Systemsitepackagessetupforskeletonproject193

TTablesdictionariesaslookup144truth97ndash98

Templatescreatebasic219ndash221creategameengine239ndash241createHTMLforms229createlayout229ndash230

templatesindexhtmlfile219ndash221229ndash230templateslayouthtmlfile230TensorFlow244Terminalgettingopenandworking250ndash251Linuxsetup5macOSsetup2ndash3typingcodeinto50whatyoushouldseeinfirstprogram9ndash11Windowssetup3ndash4

Terminologytruth96ndash97webapplication225ndash226

Testcasewriting200ndash201Testfirstprogrammingtactic206ndash207Test_directionstestcase207ndash209TestsSeealsoAutomatedtestsBooleanlogic100ndash102

codeforclassesinOOP168ndash169object-orientedreading153ndash155otherprogrammerrsquoscode94session-basedgameengine241skeletonprojectdirectorysetup197ndash198tricksforcreatingfakesessionsinside242

testsapp_testspy231Testtxtfilecopyingfiles56ndash58Textreadingfiles48ndash50andstrings26ndash27

Texteditorsalternative6ndash7gettingcolorsin12Linuxsetup4ndash5macOSsetup2

Thingsgettingthingsfrom149ndash150TopdownprocessOOPdesign164vsbottomup169

touchcommandmakeemptyfilesinmacOSLinux271ndash272Tracingvariablesreadingcode132Triple-quotes()See(triple-quotes)Triple-single-quotes()36Truekeywordavoidputtingquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98astruthterm97

truncatecommand52ndash54Truthtables97ndash98terms96ndash97

try-exceptif-elsevs209

trykeywordexceptions206Tupleslexicon205typecommandprintwholefileinWindows252

UUnderscore(_)character20ndash2162189Unicode81URLs(UniformResourceLocators)buildfirstwebsite218createHTMLforms228howformswork227overviewof225

UserinputSeeInputadvanceduserUserWarningwhenrunningnosetests203UTF-16standard84ndash85UTF-8standardcomparingUTF-16UTF-32to84ndash85dissectingoutput82encodingtextinPython81fixingterminalunabletodisplay79stringsinPython82ndash84

VValueErrorsandnumbers206parametersunpackingvariables44promptingpassing47

Variablesaccessinmodule146ndash147avoidmoduleorglobal189andfunctions64ndash66for-loopusingundefined114andnames20ndash22andnamescodefunctions60ndash62passingtoscript42ndash44

practicing90ndash93printing24ndash25promptingandpassing46ndash47readingcode132temporarilyinsidefunctions87ndash88writingstringswithtext26ndash27

venvsdirectoryskeletonprojectsetup193ndash195VerbsanalyzeclasshierarchyinOOP165extractkeyconceptsinOOP164makesentenceswith210ndash211parsercode212ndash215

virtualenv192ndash193194

WWarningsforbeginners5ndash6setup2

Webbreakingapplications232howitworks224ndash226learnclientsideof244startofyourgameSeeGamestartofyourweb

Websiteyourfirstcreatebasictemplates219ndash221fixingerrors218ndash219installflaskframework216makeldquoHelloWorldrdquowebapplication216ndash217whatisgoingon218

while-loops

overviewof116ndash118readingcode132rules126whentobreakruleaboutnotusing138

whileTruemakeinfiniteloop124Windows

Windowsalternativetexteditorsfor7setupexercise3ndash4skeletonprojectdirectorysetup194ndash195

Windowscommand-linecatstreamfile259ndash261278ndash279cpcopyfileordirectory272ndash275exitexitshell282gettingPowerShellopenandworkingfor250ndash251listofcommands252ndash253lslistdirectory262ndash265macOSsetup2moreviewfile278mvmovefileordirectory275ndash277pushdpopd(movedirectory)269ndash271pwdprintworkingdirectory254ndash255rmstreamfile278ndash279rmdirremovedirectory266ndash268

Worddrillsobject-oriented152ndash155wordspopfunction93Writeformulasusingfunctions74andreadfiles52ndash54

Xxargscommandexecutearguments252

CodeSnippets

ManytitlesincludeprogrammingcodeorconfigurationexamplesTooptimizethepresentationoftheseelementsviewtheeBookinsingle-columnlandscapemodeandadjustthefontsizetothesmallestsettingInadditiontopresentingcodeandconfigurationsinthereflowabletextformatwehaveincludedimagesofthecodethatmimicthepresentationfoundintheprintbookthereforewherethereflowableformatmaycompromisethepresentationofthecodelistingyouwillseealdquoClickheretoviewcodeimagerdquolinkClickthelinktoviewtheprint-fidelitycodeimageToreturntothepreviouspageviewedclicktheBackbuttononyourdeviceorapp

  • About This eBook
  • Title Page
  • Copyright Page
  • Contents
  • Preface
    • Improvements in the Python 3 Edition
    • The Hard Way Is Easier
      • Reading and Writing
      • Attention to Detail
      • Spotting Differences
      • Ask Donrsquot Stare
      • Do Not Copy-Paste
      • Using the Included Videos
      • A Note on Practice and Persistence
        • Acknowledgments
          • Exercise 0 The Setup
            • macOS
              • macOS What You Should See
                • Windows
                  • Windows What You Should See
                    • Linux
                      • Linux What You Should See
                        • Finding Things on the Internet
                        • Warnings for Beginners
                        • Alternative Text Editors
                          • Exercise 1 A Good First Program
                            • What You Should See
                            • Study Drills
                            • Common Student Questions
                              • Exercise 2 Comments and Pound Characters
                                • What You Should See
                                • Study Drills
                                • Common Student Questions
                                  • Exercise 3 Numbers and Math
                                    • What You Should See
                                    • Study Drills
                                    • Common Student Questions
                                      • Exercise 4 Variables and Names
                                        • What You Should See
                                        • Study Drills
                                        • Common Student Questions
                                          • Exercise 5 More Variables and Printing
                                            • What You Should See
                                            • Study Drills
                                            • Common Student Questions
                                              • Exercise 6 Strings and Text
                                                • What You Should See
                                                • Study Drills
                                                • Break It
                                                • Common Student Questions
                                                  • Exercise 7 More Printing
                                                    • What You Should See
                                                    • Study Drills
                                                    • Break It
                                                    • Common Student Questions
                                                      • Exercise 8 Printing Printing
                                                        • What You Should See
                                                        • Study Drills
                                                        • Common Student Questions
                                                          • Exercise 9 Printing Printing Printing
                                                            • What You Should See
                                                            • Study Drills
                                                            • Common Student Questions
                                                              • Exercise 10 What Was That
                                                                • What You Should See
                                                                • Escape Sequences
                                                                • Study Drills
                                                                • Common Student Questions
                                                                  • Exercise 11 Asking Questions
                                                                    • What You Should See
                                                                    • Study Drills
                                                                    • Common Student Questions
                                                                      • Exercise 12 Prompting People
                                                                        • What You Should See
                                                                        • Study Drills
                                                                        • Common Student Questions
                                                                          • Exercise 13 Parameters Unpacking Variables
                                                                            • Hold Up Features Have Another Name
                                                                            • What You Should See
                                                                            • Study Drills
                                                                            • Common Student Questions
                                                                              • Exercise 14 Prompting and Passing
                                                                                • What You Should See
                                                                                • Study Drills
                                                                                • Common Student Questions
                                                                                  • Exercise 15 Reading Files
                                                                                    • What You Should See
                                                                                    • Study Drills
                                                                                    • Common Student Questions
                                                                                      • Exercise 16 Reading and Writing Files
                                                                                        • What You Should See
                                                                                        • Study Drills
                                                                                        • Common Student Questions
                                                                                          • Exercise 17 More Files
                                                                                            • What You Should See
                                                                                            • Study Drills
                                                                                            • Common Student Questions
                                                                                              • Exercise 18 Names Variables Code Functions
                                                                                                • What You Should See
                                                                                                • Study Drills
                                                                                                • Common Student Questions
                                                                                                  • Exercise 19 Functions and Variables
                                                                                                    • What You Should See
                                                                                                    • Study Drills
                                                                                                    • Common Student Questions
                                                                                                      • Exercise 20 Functions and Files
                                                                                                        • What You Should See
                                                                                                        • Study Drills
                                                                                                        • Common Student Questions
                                                                                                          • Exercise 21 Functions Can Return Something
                                                                                                            • What You Should See
                                                                                                            • Study Drills
                                                                                                            • Common Student Questions
                                                                                                              • Exercise 22 What Do You Know So Far
                                                                                                                • What You Are Learning
                                                                                                                  • Exercise 23 Strings Bytes and Character Encodings
                                                                                                                    • Initial Research
                                                                                                                    • Switches Conventions and Encodings
                                                                                                                    • Disecting the Output
                                                                                                                    • Disecting the Code
                                                                                                                    • Encodings Deep Dive
                                                                                                                    • Breaking It
                                                                                                                      • Exercise 24 More Practice
                                                                                                                        • What You Should See
                                                                                                                        • Study Drills
                                                                                                                        • Common Student Questions
                                                                                                                          • Exercise 25 Even More Practice
                                                                                                                            • What You Should See
                                                                                                                            • Study Drills
                                                                                                                            • Common Student Questions
                                                                                                                              • Exercise 26 Congratulations Take a Test
                                                                                                                                • Common Student Questions
                                                                                                                                  • Exercise 27 Memorizing Logic
                                                                                                                                    • The Truth Terms
                                                                                                                                    • The Truth Tables
                                                                                                                                    • Common Student Questions
                                                                                                                                      • Exercise 28 Boolean Practice
                                                                                                                                        • What You Should See
                                                                                                                                        • Study Drills
                                                                                                                                        • Common Student Questions
                                                                                                                                          • Exercise 29 What If
                                                                                                                                            • What You Should See
                                                                                                                                            • Study Drills
                                                                                                                                            • Common Student Questions
                                                                                                                                              • Exercise 30 Else and If
                                                                                                                                                • What You Should See
                                                                                                                                                • Study Drills
                                                                                                                                                • Common Student Questions
                                                                                                                                                  • Exercise 31 Making Decisions
                                                                                                                                                    • What You Should See
                                                                                                                                                    • Study Drills
                                                                                                                                                    • Common Student Questions
                                                                                                                                                      • Exercise 32 Loops and Lists
                                                                                                                                                        • What You Should See
                                                                                                                                                        • Study Drills
                                                                                                                                                        • Common Student Questions
                                                                                                                                                          • Exercise 33 While Loops
                                                                                                                                                            • What You Should See
                                                                                                                                                            • Study Drills
                                                                                                                                                            • Common Student Questions
                                                                                                                                                              • Exercise 34 Accessing Elements of Lists
                                                                                                                                                                • Study Drills
                                                                                                                                                                  • Exercise 35 Branches and Functions
                                                                                                                                                                    • What You Should See
                                                                                                                                                                    • Study Drills
                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                      • Exercise 36 Designing and Debugging
                                                                                                                                                                        • Rules for if-statements
                                                                                                                                                                        • Rules for Loops
                                                                                                                                                                        • Tips for Debugging
                                                                                                                                                                        • Homework
                                                                                                                                                                          • Exercise 37 Symbol Review
                                                                                                                                                                            • Keywords
                                                                                                                                                                            • Data Types
                                                                                                                                                                            • String Escape Sequences
                                                                                                                                                                            • Old Style String Formats
                                                                                                                                                                            • Operators
                                                                                                                                                                            • Reading Code
                                                                                                                                                                            • Study Drills
                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                              • Exercise 38 Doing Things to Lists
                                                                                                                                                                                • What You Should See
                                                                                                                                                                                • What Lists Can Do
                                                                                                                                                                                • When to Use Lists
                                                                                                                                                                                • Study Drills
                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                  • Exercise 39 Dictionaries Oh Lovely Dictionaries
                                                                                                                                                                                    • A Dictionary Example
                                                                                                                                                                                    • What You Should See
                                                                                                                                                                                    • What Dictionaries Can Do
                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                      • Exercise 40 Modules Classes and Objects
                                                                                                                                                                                        • Modules Are Like Dictionaries
                                                                                                                                                                                          • Classes Are Like Modules
                                                                                                                                                                                          • Objects Are Like Import
                                                                                                                                                                                          • Getting Things from Things
                                                                                                                                                                                          • A First Class Example
                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                              • Exercise 41 Learning to Speak Object-Oriented
                                                                                                                                                                                                • Word Drills
                                                                                                                                                                                                • Phrase Drills
                                                                                                                                                                                                • Combined Drills
                                                                                                                                                                                                • A Reading Test
                                                                                                                                                                                                • Practice English to Code
                                                                                                                                                                                                • Reading More Code
                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                  • Exercise 42 Is-A Has-A Objects and Classes
                                                                                                                                                                                                    • How This Looks in Code
                                                                                                                                                                                                    • About class Name(object)
                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                      • Exercise 43 Basic Object-Oriented Analysis and Design
                                                                                                                                                                                                        • The Analysis of a Simple Game Engine
                                                                                                                                                                                                          • Write or Draw About the Problem
                                                                                                                                                                                                          • Extract Key Concepts and Research Them
                                                                                                                                                                                                          • Create a Class Hierarchy and Object Map for the Concepts
                                                                                                                                                                                                          • Code the Classes and a Test to Run Them
                                                                                                                                                                                                          • Repeat and Refine
                                                                                                                                                                                                            • Top Down versus Bottom Up
                                                                                                                                                                                                            • The Code for ldquoGothons from Planet Percal 25rdquo
                                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                                              • Exercise 44 Inheritance versus Composition
                                                                                                                                                                                                                • What Is Inheritance
                                                                                                                                                                                                                  • Implicit Inheritance
                                                                                                                                                                                                                  • Override Explicitly
                                                                                                                                                                                                                  • Alter Before or After
                                                                                                                                                                                                                  • All Three Combined
                                                                                                                                                                                                                    • The Reason for super()
                                                                                                                                                                                                                      • Using super() with __init__
                                                                                                                                                                                                                        • Composition
                                                                                                                                                                                                                        • When to Use Inheritance or Composition
                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                          • Exercise 45 You Make a Game
                                                                                                                                                                                                                            • Evaluating Your Game
                                                                                                                                                                                                                            • Function Style
                                                                                                                                                                                                                            • Class Style
                                                                                                                                                                                                                            • Code Style
                                                                                                                                                                                                                            • Good Comments
                                                                                                                                                                                                                            • Evaluate Your Game
                                                                                                                                                                                                                              • Exercise 46 A Project Skeleton
                                                                                                                                                                                                                                • macOSLinux Setup
                                                                                                                                                                                                                                • Windows 10 Setup
                                                                                                                                                                                                                                • Creating the Skeleton Project Directory
                                                                                                                                                                                                                                  • Final Directory Structure
                                                                                                                                                                                                                                    • Testing Your Setup
                                                                                                                                                                                                                                    • Using the Skeleton
                                                                                                                                                                                                                                    • Required Quiz
                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                      • Exercise 47 Automated Testing
                                                                                                                                                                                                                                        • Writing a Test Case
                                                                                                                                                                                                                                        • Testing Guidelines
                                                                                                                                                                                                                                        • What You Should See
                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                          • Exercise 48 Advanced User Input
                                                                                                                                                                                                                                            • Our Game Lexicon
                                                                                                                                                                                                                                              • Breaking Up a Sentence
                                                                                                                                                                                                                                              • Lexicon Tuples
                                                                                                                                                                                                                                              • Scanning Input
                                                                                                                                                                                                                                              • Exceptions and Numbers
                                                                                                                                                                                                                                                • A Test First Challenge
                                                                                                                                                                                                                                                • What You Should Test
                                                                                                                                                                                                                                                • Study Drills
                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                  • Exercise 49 Making Sentences
                                                                                                                                                                                                                                                    • Match and Peek
                                                                                                                                                                                                                                                    • The Sentence Grammar
                                                                                                                                                                                                                                                    • A Word on Exceptions
                                                                                                                                                                                                                                                    • The Parser Code
                                                                                                                                                                                                                                                    • Playing with the Parser
                                                                                                                                                                                                                                                    • What You Should Test
                                                                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                                      • Exercise 50 Your First Website
                                                                                                                                                                                                                                                        • Installing flask
                                                                                                                                                                                                                                                        • Make a Simple ldquoHello Worldrdquo Project
                                                                                                                                                                                                                                                        • Whatrsquos Going On
                                                                                                                                                                                                                                                        • Fixing Errors
                                                                                                                                                                                                                                                        • Create Basic Templates
                                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                                          • Exercise 51 Getting Input from a Browser
                                                                                                                                                                                                                                                            • How the Web Works
                                                                                                                                                                                                                                                            • How Forms Work
                                                                                                                                                                                                                                                            • Creating HTML Forms
                                                                                                                                                                                                                                                            • Creating a Layout Template
                                                                                                                                                                                                                                                            • Writing Automated Tests for Forms
                                                                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                                                                            • Breaking It
                                                                                                                                                                                                                                                              • Exercise 52 The Start of Your Web Game
                                                                                                                                                                                                                                                                • Refactoring the Exercise 43 Game
                                                                                                                                                                                                                                                                • Creating an Engine
                                                                                                                                                                                                                                                                • Your Final Exam
                                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                                  • Next Steps
                                                                                                                                                                                                                                                                    • How to Learn Any Programming Language
                                                                                                                                                                                                                                                                      • Advice from an Old Programmer
                                                                                                                                                                                                                                                                      • Appendix Command Line Crash Course
                                                                                                                                                                                                                                                                        • Introduction Shut Up and Shell
                                                                                                                                                                                                                                                                          • How to Use This Appendix
                                                                                                                                                                                                                                                                          • You Will Be Memorizing Things
                                                                                                                                                                                                                                                                            • The Setup
                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                • Paths Folders Directories (pwd)
                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                    • If You Get Lost
                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                        • Make a Directory (mkdir)
                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                            • Change Directory (cd)
                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                • List Directory (ls)
                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                    • Remove Directory (rmdir)
                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                        • Moving Around (pushd popd)
                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                            • Making Empty Files (touchNew-Item)
                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                • Copy a File (cp)
                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                    • Moving a File (mv)
                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                        • View a File (lessmore)
                                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                                            • Stream a File (cat)
                                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                                • Removing a File (rm)
                                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                                    • Exiting Your Terminal (exit)
                                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                                        • Command Line Next Steps
                                                                                                                                                                                                                                                                                                                                          • Unix Bash References
                                                                                                                                                                                                                                                                                                                                          • PowerShell References
                                                                                                                                                                                                                                                                                                                                              • Index
                                                                                                                                                                                                                                                                                                                                              • Code Snippets
Page 4: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code

Contents

Preface

ImprovementsinthePython3EditionTheHardWayIsEasier

ReadingandWritingAttentiontoDetailSpottingDifferencesAskDonrsquotStareDoNotCopy-PasteUsingtheIncludedVideosANoteonPracticeandPersistence

Acknowledgments

Exercise0TheSetupmacOS

macOSWhatYouShouldSeeWindows

WindowsWhatYouShouldSeeLinux

LinuxWhatYouShouldSeeFindingThingsontheInternetWarningsforBeginnersAlternativeTextEditors

Exercise1AGoodFirstProgramWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise2CommentsandPoundCharactersWhatYouShouldSee

StudyDrillsCommonStudentQuestions

Exercise3NumbersandMathWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise4VariablesandNamesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise5MoreVariablesandPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise6StringsandTextWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise7MorePrintingWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise8PrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise9PrintingPrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise10WhatWasThatWhatYouShouldSeeEscapeSequencesStudyDrillsCommonStudentQuestions

Exercise11AskingQuestionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise12PromptingPeopleWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise13ParametersUnpackingVariablesHoldUpFeaturesHaveAnotherNameWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise14PromptingandPassingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise15ReadingFilesWhatYouShouldSeeStudyDrills

CommonStudentQuestions

Exercise16ReadingandWritingFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise17MoreFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise18NamesVariablesCodeFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise19FunctionsandVariablesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise20FunctionsandFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise21FunctionsCanReturnSomethingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise22WhatDoYouKnowSoFarWhatYouAreLearning

Exercise23StringsBytesandCharacterEncodings

InitialResearchSwitchesConventionsandEncodingsDisectingtheOutputDisectingtheCodeEncodingsDeepDiveBreakingIt

Exercise24MorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise25EvenMorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise26CongratulationsTakeaTestCommonStudentQuestions

Exercise27MemorizingLogicTheTruthTermsTheTruthTablesCommonStudentQuestions

Exercise28BooleanPracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise29WhatIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise30ElseandIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise31MakingDecisionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise32LoopsandListsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise33WhileLoopsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise34AccessingElementsofListsStudyDrills

Exercise35BranchesandFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise36DesigningandDebuggingRulesforif-statementsRulesforLoopsTipsforDebuggingHomework

Exercise37SymbolReview

KeywordsDataTypesStringEscapeSequencesOldStyleStringFormatsOperatorsReadingCodeStudyDrillsCommonStudentQuestions

Exercise38DoingThingstoListsWhatYouShouldSeeWhatListsCanDoWhentoUseListsStudyDrillsCommonStudentQuestions

Exercise39DictionariesOhLovelyDictionariesADictionaryExampleWhatYouShouldSeeWhatDictionariesCanDoStudyDrillsCommonStudentQuestions

Exercise40ModulesClassesandObjectsModulesAreLikeDictionaries

ClassesAreLikeModulesObjectsAreLikeImportGettingThingsfromThingsAFirstClassExample

WhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise41LearningtoSpeakObject-OrientedWordDrillsPhraseDrillsCombinedDrillsAReadingTestPracticeEnglishtoCodeReadingMoreCodeCommonStudentQuestions

Exercise42Is-AHas-AObjectsandClassesHowThisLooksinCodeAboutclassName(object)StudyDrillsCommonStudentQuestions

Exercise43BasicObject-OrientedAnalysisandDesignTheAnalysisofaSimpleGameEngine

WriteorDrawAbouttheProblemExtractKeyConceptsandResearchThemCreateaClassHierarchyandObjectMapfortheConceptsCodetheClassesandaTesttoRunThemRepeatandRefine

TopDownversusBottomUpTheCodeforldquoGothonsfromPlanetPercal25rdquoWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise44InheritanceversusCompositionWhatIsInheritance

ImplicitInheritanceOverrideExplicitlyAlterBeforeorAfter

AllThreeCombinedTheReasonforsuper()

Usingsuper()with__init__CompositionWhentoUseInheritanceorCompositionStudyDrillsCommonStudentQuestions

Exercise45YouMakeaGameEvaluatingYourGameFunctionStyleClassStyleCodeStyleGoodCommentsEvaluateYourGame

Exercise46AProjectSkeletonmacOSLinuxSetupWindows10SetupCreatingtheSkeletonProjectDirectory

FinalDirectoryStructureTestingYourSetupUsingtheSkeletonRequiredQuizCommonStudentQuestions

Exercise47AutomatedTestingWritingaTestCaseTestingGuidelinesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise48AdvancedUserInputOurGameLexicon

BreakingUpaSentenceLexiconTuplesScanningInputExceptionsandNumbers

ATestFirstChallengeWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise49MakingSentencesMatchandPeekTheSentenceGrammarAWordonExceptionsTheParserCodePlayingwiththeParserWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise50YourFirstWebsiteInstallingflaskMakeaSimpleldquoHelloWorldrdquoProjectWhatrsquosGoingOnFixingErrorsCreateBasicTemplatesStudyDrillsCommonStudentQuestions

Exercise51GettingInputfromaBrowserHowtheWebWorksHowFormsWork

CreatingHTMLFormsCreatingaLayoutTemplateWritingAutomatedTestsforFormsStudyDrillsBreakingIt

Exercise52TheStartofYourWebGameRefactoringtheExercise43GameCreatinganEngineYourFinalExamCommonStudentQuestions

NextStepsHowtoLearnAnyProgrammingLanguage

AdvicefromanOldProgrammer

AppendixCommandLineCrashCourseIntroductionShutUpandShell

HowtoUseThisAppendixYouWillBeMemorizingThings

TheSetupDoThisYouLearnedThisDoMore

PathsFoldersDirectories(pwd)DoThisYouLearnedThisDoMore

IfYouGetLostDoThisYouLearnedThis

MakeaDirectory(mkdir)DoThis

YouLearnedThisDoMore

ChangeDirectory(cd)DoThisYouLearnedThisDoMore

ListDirectory(ls)DoThisYouLearnedThisDoMore

RemoveDirectory(rmdir)DoThisYouLearnedThisDoMore

MovingAround(pushdpopd)DoThisYouLearnedThisDoMore

MakingEmptyFiles(touchNew-Item)DoThisYouLearnedThisDoMore

CopyaFile(cp)DoThisYouLearnedThisDoMore

MovingaFile(mv)DoThisYouLearnedThisDoMore

ViewaFile(lessmore)

DoThisYouLearnedThisDoMore

StreamaFile(cat)DoThisYouLearnedThisDoMore

RemovingaFile(rm)DoThisYouLearnedThisDoMore

ExitingYourTerminal(exit)DoThisYouLearnedThisDoMore

CommandLineNextStepsUnixBashReferencesPowerShellReferences

Index

Preface

ThissimplebookismeanttogetyoustartedinprogrammingThetitlesaysitrsquosthehardwaytolearntowritecodebutitrsquosactuallynotItrsquosonlytheldquohardrdquowaybecauseitusesatechniquecalledinstructionInstructioniswhereItellyoutodoasequenceofcontrolledexercisesdesignedtobuildaskillthroughrepetitionThistechniqueworksverywellwithbeginnerswhoknownothingandneedtoacquirebasicskillsbeforetheycanunderstandmorecomplextopicsItrsquosusedineverythingfrommartialartstomusictoevenbasicmathandreadingskillsThisbookinstructsyouinPythonbyslowlybuildingandestablishingskillsthroughtechniquessuchaspracticeandmemorizationthenapplyingthemtoincreasinglydifficultproblemsBytheendofthebookyouwillhavethetoolsneededtobeginlearningmorecomplexprogrammingtopicsIliketotellpeoplethatmybookgivesyouyourldquoprogrammingblackbeltrdquoWhatthismeansisthatyouknowthebasicswellenoughtonowstartlearningprogrammingIfyouworkhardtakeyourtimeandbuildtheseskillsyouwilllearntocode

ImprovementsinthePython3EditionLearnPython3theHardWaynowusesPython36IrsquovestandardizedonthisversionofPythonbecauseithasanewimprovedstringformattingsystemthatiseasiertousethantheprevious4(or3Iforgetthereweremany)versionsThereareafewproblemswithPython36forbeginnersbutIhelpyounavigatetheseissuesinthebookAparticularlyhairyproblemisthatPython36hasverypoorerrormessagesinsomekeyareasthatIhelpyouunderstandIhavealsoimprovedthevideosbasedonmyexperiencesoverthelastfiveyearsteachingpeoplePythonYoucanwatchthesevideosonlineatinformitcomtitle9780134692883InthepastthevideossimplyletyouwatchmedotheexerciseThePython3editionvideosalsoshowyouhowtobreakmdashandthenfixmdasheveryexerciseThisskilliscalledldquodebuggingrdquoItteachesyouhowtofixproblemsyourunintobutalsohowPythonrunstheprogramsyoursquorecreatingThegoalofthisnewmethodologyistobuildamentalmodelofhowPythonrunsyourcodesoyoucanmoreeasilyfigureoutwhyitrsquosbrokenYoursquollalsolearnmanyusefultricksfordebuggingbrokensoftwareLastthePython3editionfullysupportsMicrosoftWindows10frombeginningtoendThepreviouseditionfocusedmostlyontheUnix-stylesystemssuchasmacOSandLinuxwithWindowsbeingmoreofanafterthoughtAtthetimeIstartedwritingthePython3editionMicrosofthadstartedtotakeopensource

startedwritingthePython3editionMicrosofthadstartedtotakeopensourcetoolsanddevelopersseriouslyanditwasdifficulttoignorethemasaseriousPythondevelopmentplatformThevideosfeatureMicrosoftWindowsusingPythoninvariousscenariosandalsoshowmacOSandLinuxforfullcompatibilityItellyouaboutanygotchasoneachplatformcoverinstallationinstructionsandprovideanyothertipsIcangiveyou

TheHardWayIsEasierWiththehelpofthisbookyouwilldotheincrediblysimplethingsthatallprogrammersdotolearnaprogramminglanguage

1Gothrougheachexercise2Typeineachfileexactly3Makeitrun

ThatrsquositThiswillbeverydifficultatfirstbutstickwithitIfyougothroughthisbookanddoeachexerciseforoneortwohoursanightyouwillhaveagoodfoundationformovingontoanotherbookaboutPythontocontinueyourstudiesThisbookwonrsquotturnyouintoaprogrammerovernightbutitwillgetyoustartedonthepathtolearninghowtocodeThisbookrsquosjobistoteachyouthethreemostessentialskillsthatabeginningprogrammerneedstoknowreadingandwritingattentiontodetailandspottingdifferences

ReadingandWritingIfyouhaveaproblemtypingyouwillhaveaproblemlearningtocodeespeciallyifyouhaveaproblemtypingthefairlyoddcharactersinsourcecodeWithoutthissimpleskillyouwillbeunabletolearneventhemostbasicthingsabouthowsoftwareworksTypingthecodesamplesandgettingthemtorunwillhelpyoulearnthenamesofthesymbolsgetfamiliarwithtypingthemandgetyoureadingthelanguage

AttentiontoDetailTheoneskillthatseparatesgoodprogrammersfrombadprogrammersisattentiontodetailInfactitrsquoswhatseparatesthegoodfromthebadinanyprofessionYoumustpayattentiontothetiniestdetailsofyourworkoryouwillmissimportantelementsofwhatyoucreateInprogrammingthisishowyouendupwithbugsanddifficult-to-usesystemsBygoingthroughthisbookandcopyingeachexampleexactlyyouwillbetrainingyourbraintofocusonthedetailsofwhatyouaredoingasyouare

doingit

SpottingDifferencesAveryimportantskill(thatmostprogrammersdevelopovertime)istheabilitytovisuallynoticedifferencesbetweenthingsAnexperiencedprogrammercantaketwopiecesofcodethatareslightlydifferentandimmediatelystartpointingoutthedifferencesProgrammershaveinventedtoolstomakethiseveneasierbutwewonrsquotbeusinganyoftheseYoufirsthavetotrainyourbrainthehardwaythenusethetoolsWhileyoudotheseexercisestypingeachoneinyouwillmakemistakesItrsquosinevitableevenseasonedprogrammerswouldmakeafewYourjobistocomparewhatyouhavewrittentowhatrsquosrequiredandfixallthedifferencesBydoingsoyouwilltrainyourselftonoticemistakesbugsandotherproblems

AskDonrsquotStareIfyouwritecodeyouwillwritebugsAldquobugrdquomeansadefecterrororproblemwiththecodeyoursquovewrittenThelegendssaythatthiscomesfromanactualmoththatflewintooneofthefirstcomputerscausingittomalfunctionFixingitrequiredldquodebuggingrdquothecomputerIntheworldofsoftwaretherearealotofbugsSomanyLikethatfirstmothyourbugswillbehiddensomewhereinthecodeandyouhavetogofindthemYoucanrsquotjustsitatyourcomputerscreenstaringatthewordsyoursquovewrittenhopingthattheanswerjumpsoutatyouThereisnomoreadditionalinformationyoucangetdoingthatandyouneedadditionalinformationYouneedtogetupandgofindthemothTodothatyouhavetointerrogateyourcodeandaskitwhatisgoingonorlookattheproblemfromadifferentviewInthisbookIfrequentlytellyoutoldquostopstaringandaskrdquoIshowyouhowtomakeyourcodetellyoueverythingitcanaboutwhatrsquosgoingonandhowtoturnthisintopossiblesolutionsIalsoshowyouhowtoseeyourcodeindifferentwayssoyoucangetmoreinformationandinsight

DoNotCopy-PasteYoumusttypeeachoftheseexercisesinmanuallyIfyoucopy-pasteyoumightaswellnotevendothemThepointoftheseexercisesistotrainyourhandsyourbrainandyourmindinhowtoreadwriteandseecodeIfyoucopy-pasteyouarecheatingyourselfoutoftheeffectivenessofthelessons

UsingtheIncludedVideos

LearnPython3theHardWayhasanextensivesetofvideosdemonstratinghowthecodeworksandmostimportantlyhowtobreakitThevideosaretheperfectplacetodemonstratemanycommonerrorsbybreakingthePythoncodeonpurposeandshowingyouhowtofixitIalsowalkthroughthecodeusingdebuggingandinterrogationtricksandtechniquesThevideosarewhereIshowyouhowtoldquostopstaringandaskrdquothecodewhatrsquoswrongYoucanwatchthesevideosonlineatinformitcomtitle9780134692883

ANoteonPracticeandPersistenceWhileyouarestudyingprogrammingIrsquomstudyinghowtoplayguitarIpracticeiteverydayforatleasttwohoursadayIplayscaleschordsandarpeggiosforanhourandthenlearnmusictheoryeartrainingsongsandanythingelseIcanSomedaysIstudyguitarandmusicforeighthoursbecauseIfeellikeitanditrsquosfunTomerepetitivepracticeisnaturalandjusthowtolearnsomethingIknowthattogetgoodatanythingIhavetopracticeeverydayevenifIsuckthatday(whichisoften)oritrsquosdifficultKeeptryingandeventuallyitrsquollbeeasierandfunBetweenthetimethatIwroteLearnPythontheHardWayandLearnRubytheHardWayIdiscovereddrawingandpaintingIfellinlovewithmakingvisualartattheageof39andhavebeenspendingeverydaystudyingitinmuchthesamewaythatIstudiedguitarmusicandprogrammingIcollectedbooksofinstructionalmaterialdidwhatthebookssaidpaintedeverydayandfocusedonenjoyingtheprocessoflearningIambynomeansanldquoartistrdquooreventhatgoodbutIcannowsaythatIcandrawandpaintThesamemethodIrsquomteachingyouinthisbookappliedtomyadventuresinartIfyoubreaktheproblemdownintosmallexercisesandlessonsanddothemeverydayyoucanlearntodoalmostanythingIfyoufocusonslowlyimprovingandenjoyingthelearningprocessthenyouwillbenefitnomatterhowgoodyouareatitAsyoustudythisbookandcontinuewithprogrammingrememberthatanythingworthdoingisdifficultatfirstMaybeyouarethekindofpersonwhoisafraidoffailuresoyougiveupatthefirstsignofdifficultyMaybeyouneverlearnedself-disciplinesoyoucanrsquotdoanythingthatrsquosldquoboringrdquoMaybeyouweretoldthatyouareldquogiftedrdquosoyouneverattemptanythingthatmightmakeyouseemstupidornotaprodigyMaybeyouarecompetitiveandunfairlycompareyourselftosomeonelikemewhorsquosbeenprogrammingformorethan20yearsWhateveryourreasonforwantingtoquitkeepatitForceyourselfIfyourunintoaStudyDrillyoucanrsquotdooralessonyoujustdonotunderstandthenskip

itandcomebacktoitlaterJustkeepgoingbecausewithprogrammingtherersquosthisveryoddthingthathappensAtfirstyouwillnotunderstandanythingItrsquollbeweirdjustlikewithlearninganyhumanlanguageYouwillstrugglewithwordsandnotknowwhatsymbolsarewhatanditrsquollallbeveryconfusingThenonedayBANGmdashyourbrainwillsnapandyouwillsuddenlyldquogetitrdquoIfyoukeepdoingtheexercisesandkeeptryingtounderstandthemyouwillgetitYoumightnotbeamastercoderbutyouwillatleastunderstandhowprogrammingworksIfyougiveupyouwonrsquoteverreachthispointYouwillhitthefirstconfusingthing(whichiseverythingatfirst)andthenstopIfyoukeeptryingkeeptypingitinkeeptryingtounderstanditandreadingaboutityouwilleventuallygetitIfyougothroughthiswholebookandyoustilldonotunderstandhowtocodeatleastyougaveitashotYoucansayyoutriedyourbestandalittlemoreanditdidnrsquotworkoutbutatleastyoutriedYoucanbeproudofthat

RegisteryourcopyofLearnPython3theHardWayontheInformITsiteforconvenientaccesstoupdatesandcorrectionsastheybecomeavailableTostarttheregistrationprocessgotoinformitcomregisterandloginorcreateanaccountEntertheproductISBN(9780134692883)andanswerthesimpleproof-of-purchasequestionThenlookontheRegisteredProductstabforanAccessBonusContentlinknexttothisproductandfollowthatlinktoaccessthebonusmaterials

AcknowledgmentsIwouldliketothankAngelaforhelpingmewiththefirsttwoversionsofthisbookWithoutherIprobablywouldnrsquothavebotheredtofinishitatallShedidthecopyeditingofthefirstdraftandsupportedmeimmenselywhileIwroteitIrsquodalsoliketothankGregNewmanfordoingtheoriginalcoverartBrianShumateforearlywebsitedesignsandallofthepeoplewhoreadthisbookandtookthetimetosendmefeedbackandcorrectionsThankyou

Exercise0TheSetup

ThisexercisehasnocodeItissimplytheexerciseyoucompletetogetyourcomputertorunPythonYoushouldfollowtheseinstructionsasexactlyaspossibleIfyouhaveproblemsfollowingthewritteninstructionsthenwatchtheincludedvideosforyourplatform

WarningIfyoudonotknowhowtousePowerShellonWindowsTerminalonmacOSorbashonLinuxthenyouneedtogolearnthatfirstYoushoulddotheexercisesintheappendixfirstbeforecontinuingwiththeseexercises

macOSDothefollowingtaskstocompletethisexercise

1Gotohttpswwwpythonorgdownloadsreleasepython-360anddownloadtheversiontitledldquoMacOSX64-bit32-bitinstallerrdquoInstallitlikeyouwouldanyothersoftware

2GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3PutAtom(yourtexteditor)inyourdocksoyoucanreachiteasily4FindyourTerminalprogramSearchforitYouwillfindit5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthenameandhittingRETURN

8Typequit()Enterandgetoutofpython369YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryintheTerminal11LearnhowtochangeintoadirectoryintheTerminal12UseyoureditortocreateafileinthisdirectoryMakethefileSaveor

SaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindows14BackinTerminallistthedirectorywithlstoseeyournewlycreatedfile

macOSWhatYouShouldSeeHerersquosmedoingthisonmymacOScomputerinTerminalYourcomputermightbedifferentbutshouldbesimilartothisClickheretoviewcodeimage

$python36

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clangndash700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgt

~$mkdirlpthw

~$cdlpthw

lpthw$ls

Useyourtexteditorheretoedittesttxt

lpthw$ls

testtxt

lpthw$

Windows1GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitYoudonotneedtobetheadministratortodothis

2MakesureyoucangettoAtomeasilybyputtingitonyourdesktopandorinQuickLaunchBothoptionsareavailableduringsetupIfyoucannotrunAtombecauseyourcomputerisnotfastenoughthenseetheAlternativeTextEditorssectionattheendofthisexercise

3RunPowerShellfromtheStartmenuSearchforitandjustpressEntertorunit

4MakeashortcuttoitonyourdesktopandorQuickLaunchforyourconvenience

5RunyourPowerShellprogram(whichIwillcallTerminallater)Itwonrsquotlooklikemuch

6DownloadPython36fromhttpswwwpythonorgdownloadsreleasepython-360andinstallitBesuretochecktheboxthatsaystoaddPython36toyourpath

7InyourPowerShell(Terminal)programrunpythonYourunthingsinTerminalbyjusttypingthenameandpressingEnterIfyoutypepythonanditdoesnotrunthenyouhavetoreinstallPythonandmakesureyouchecktheboxforldquoAddpythontothePATHrdquoItrsquosverysmallsolookcarefully

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinthePowerShell(Terminal)11LearnhowtochangeintoadirectoryinthePowerShell(Terminal)12UseyoureditortocreateafileinthisdirectoryMakethefileSaveorSaveAsandpickthisdirectory

13GobacktoPowerShell(Terminal)usingjustthekeyboardtoswitchwindowsLookitupifyoucanrsquotfigureitout

14BackinPowerShell(Terminal)listthedirectorytoseeyournewlycreatedfile

FromnowonwhenIsayldquoTerminalrdquoorldquoshellrdquoImeanPowerShellandthatrsquoswhatyoushoulduseWhenIrunpython36youcanjusttypepython

WindowsWhatYouShouldSeeClickheretoviewcodeimage

gtpython

gtgtgtquit()

gtmkdirlpthw

gtcdlpthw

Hereyouwoulduseyourtexteditortomaketesttxtinlpthw

gt

gtdir

VolumeindriveCis

VolumeSerialNumberis085C-7E02

DirectoryofCDocumentsandSettingsyoulpthw

040520102332ltDIRgt

040520102332ltDIRgt

0405201023326testtxt

1File(s)6bytes

2Dir(s)14804623360bytesfree

gt

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

LinuxLinuxisavariedoperatingsystemwithmanydifferentwaystoinstallsoftwareIrsquomassumingifyouarerunningLinuxthenyouknowhowtoinstallpackagessohereareyourinstructions

1UseyourpackagemanagertoinstallPython36andifyoucanrsquotthendownloadsourcefromhttpswwwpythonorgdownloadsreleasepython-360andbuildfromsource

2UseyourLinuxpackagemanagerandinstalltheAtomtexteditorIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3MakesureyoucangettoAtomeasilybyputtingitinyourwindowmanagerrsquosmenu

4FindyourTerminalprogramItcouldbecalledGNOMETerminalKonsoleorxterm

5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthecommandnameandpressingEnterIfyoucanrsquotrunpython36tryrunningjustpython

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinTerminal11LearnhowtochangeintoadirectoryinTerminal12UseyoureditortocreateafileinthisdirectoryTypicallyyouwillmake

thefileSaveorSaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindowsLookit

upifyoucanrsquotfigureitout14BackinTerminallistthedirectorytoseeyournewlycreatedfile

LinuxWhatYouShouldSee

Clickheretoviewcodeimage

$python

gtgtgtquit()

$mkdirlpthw

$cdlpthw

Useyourtexteditorheretoedittesttxt

$ls

testtxt

$

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

FindingThingsontheInternetAmajorpartofthisbookislearningtoresearchprogrammingtopicsonlineIrsquolltellyoutoldquosearchforthisontheinternetrdquoandyourjobistouseasearchenginetofindtheanswerThereasonIhaveyousearchinsteadofjustgivingyoutheanswerisbecauseIwantyoutobeanindependentlearnerwhodoesnotneedmybookwhenyoursquoredonewithitIfyoucanfindtheanswerstoyourquestionsonlinethenyouareonestepclosertonotneedingmeandthatismygoalThankstosearchenginessuchasGoogleyoucaneasilyfindanythingItellyoutofindIfIsayldquosearchonlineforthepythonlistfunctionsrdquothenyousimplydothis

1Gotohttpgooglecom2Typepython3listfunctions3Readthewebsiteslistedtofindthebestanswer

WarningsforBeginnersYouaredonewiththisexerciseThisexercisemightbehardforyoudependingonyourfamiliaritywithyourcomputerIfitisdifficulttakethetimetoreadandstudyandgetthroughitbecauseuntilyoucandotheseverybasicthingsyouwillfinditdifficulttogetmuchprogrammingdoneIfsomeonetellsyoutostopataspecificexerciseinthisbookortoskipcertainonesyoushouldignorethatpersonAnyonetryingtohideknowledgefromyouorworsemakeyougetitfromtheminsteadofthroughyourowneffortsistryingtomakeyoudependonthemforyourskillsDonrsquotlistentothemanddotheexercisesanywaysothatyoulearnhowtoeducateyourselfAprogrammerwilleventuallytellyoutousemacOSorLinuxIftheprogrammerlikesfontsandtypographytheyrsquolltellyoutogetamacOScomputerIfhelikescontrolandhasahugebeardhewill(orzewillifyou

computerIfhelikescontrolandhasahugebeardhewill(orzewillifyouprefernon-genderedpronounsforhumanswithbeards)tellyoutoinstallLinuxAgainusewhatevercomputeryouhaverightnowthatworksAllyouneedisaneditoraTerminalandPythonFinallythepurposeofthissetuphelpsyoudothreethingsveryreliablywhileyouworkontheexercises

1Writeexercisesusingthetexteditor2Runtheexercisesyouwrote3Fixthemwhentheyarebroken4Repeat

Anythingelsewillonlyconfuseyousosticktotheplan

AlternativeTextEditorsTexteditorsareveryimportanttoaprogrammerbutasabeginneryouonlyneedasimpleprogrammerrsquostexteditorThesearedifferentfromsoftwareforwritingstoriesandbooksbecausetheyworkwiththeuniqueneedsofcomputercodeIrecommendAtominthisbookbecauseitisfreeandworksnearlyeverywhereHoweverAtommaynotrunwellonyourcomputersoherearesomealternativestotry

ThesearerankedinorderofmostlikelytoworkKeepinmindthattheseprojectsmaybeabandoneddeadornotworkanymoreonyourcomputerIfyoutryoneanditdoesnrsquotworktryanotheroneIrsquovealsolistedtheldquoWorksOnrdquoinorderofmostlikelytoworksoifyoursquoreonWindowsthenlookattheeditorswhereWindowsislistedfirstintheldquoWorksOnrdquocolumnIfyoualreadyknowhowtouseVimorEmacsthenfeelfreetousethemIfyouhaveneverusedVimorEmacsthenavoidthemProgrammersmaytrytoconvinceyoutouseVimorEmacsbutthiswillonlyderailyouYourfocusislearningPythonnotlearningVimorEmacsIfyoutrytouseVimanddonrsquotknowhowtoquitthentypeqorZZIfsomeonetoldyoutouseVimand

theydidnrsquoteventellyouthisthennowyouknowwhyyoushouldnrsquotlistentothemDonotuseanIntegratedDevelopmentEnvironment(IDE)whileyougothroughthisbookRelyingonanIDEmeansthatyoucanrsquotworkwithnewprogramminglanguagesuntilsomecompanydecidestosellyouanIDEforthatlanguageThismeansyoucanrsquotusethatnewlanguageuntilthelanguageislargeenoughtojustifyalucrativecustomerbaseIfyouareconfidentyoucanworkwithonlyaprogrammerrsquostexteditor(likeVimEmacsAtometc)thenyoudonrsquothavetowaitforathirdpartyIDEsareniceinsomesituations(suchasworkingwithagiantexistingcodebase)butbeingaddictedtothemwilllimityourfutureYoushouldalsonotuseIDLEIthasseriouslimitationsinhowitworksandisnrsquotaverygoodpieceofsoftwareAllyouneedisasimpletexteditorashellandPython

Exercise1AGoodFirstProgram

WarningIfyouskippedExercise0thenyouarenotdoingthisbookrightAreyoutryingtouseIDLEoranIDEIsaidnottouseoneinExercise0soyoushouldnotuseoneIfyouskippedExercise0pleasegobacktoitandreadit

YoushouldhavespentagoodamountoftimeinExercise0learninghowtoinstallatexteditorrunthetexteditorruntheTerminalandworkwithbothofthemIfyouhavenrsquotdonethatthendonotgoonYouwillnothaveagoodtimeThisistheonlytimeIrsquollstartanexercisewithawarningthatyoushouldnotskiporgetaheadofyourselfTypethefollowingtextintoasinglefilenamedex1pyPythonworksbestwithfilesendinginpyClickheretoviewcodeimage

ex1py

1print(HelloWorld)

2print(HelloAgain)

3print(Iliketypingthis)

4print(Thisisfun)

5print(YayPrinting)

6print(Idmuchratheryounot)

7print(Isaiddonottouchthis)

YourAtomtexteditorshouldlooksomethinglikethisonallplatforms

DonrsquotworryifyoureditordoesnrsquotlookexactlythesameitshouldbeclosethoughYoumayhaveaslightlydifferentwindowheadermaybeslightlydifferentcolorsandtheleftsideofyourAtomwindowwonrsquotsayldquozedshawrdquobutwillinsteadshowthedirectoryyouusedforsavingyourfilesAllofthosedifferencesarefineWhenyoucreatethisfilekeepinmindthesepoints

1IdidnottypethelinenumbersontheleftThoseareprintedinthebooksoIcantalkaboutspecificlinesbysayingldquoSeeline5rdquoYoudonottypelinenumbersintoPythonscripts

2IhavetheprintatthebeginningofthelineanditlooksexactlythesameaswhatIhaveinex1pyExactlymeansexactlynotkindofsortofthesameEverysinglecharacterhastomatchforittoworkColordoesnrsquot

matteronlythecharactersyoutypeInmacOSTerminalor(maybe)Linuxrunthefilebytyping

python36ex1py

OnWindowsrememberyoualwaystypepythoninsteadofpython36likethis

pythonex1py

IfyoudiditrightthenyoushouldseethesameoutputasIintheWhatYouShouldSeesectionofthisexerciseIfnotyouhavedonesomethingwrongNothecomputerisnotwrong

WhatYouShouldSeeOnmacOSintheTerminalyoushouldseethis

OnWindowsinPowerShellyoushouldseethis

Youmayseedifferentnamesbeforethepython36ex1pycommandbuttheimportantpartisthatyoutypethecommandandseetheoutputisthesameasmineIfyouhaveanerroritwilllooklikethisClickheretoviewcodeimage

$python36pythonex1py

Filepythonex1pyline3

print(Iliketypingthis

^

SyntaxErrorEOLwhilescanningstringliteral

ItrsquosimportantthatyoucanreadtheseerrormessagesbecauseyouwillbemakingmanyofthesemistakesEvenImakemanyofthesemistakesLetrsquoslookatthislinebyline

1WeranourcommandintheTerminaltoruntheex1pyscript2Pythontellsusthatthefileex1pyhasanerroronline3ofex1py3Itprintsthislineofcodeforustoseeit4Thenitputsa^(caret)charactertopointatwheretheproblemisNoticethemissing(double-quote)character

5FinallyitprintsoutaldquoSyntaxErrorrdquoandtellsussomethingaboutwhatmightbetheerrorUsuallytheseareverycrypticbutifyoucopythattext

mightbetheerrorUsuallytheseareverycrypticbutifyoucopythattextintoasearchengineyouwillfindsomeoneelsewhorsquoshadthaterrorandyoucanprobablyfigureouthowtofixit

StudyDrillsTheStudyDrillscontainthingsyoushouldtrytodoIfyoucanrsquotskipitandcomebacklaterForthisexercisetrythesethings

1Makeyourscriptprintanotherline2Makeyourscriptprintonlyoneofthelines3Puta(octothorpe)characteratthebeginningofalineWhatdiditdoTrytofindoutwhatthischaracterdoes

FromnowonIwonrsquotexplainhoweachexerciseworksunlessanexerciseisdifferent

WarningAnldquooctothorperdquoisalsocalledaldquopoundrdquoldquohashrdquoldquomeshrdquooranynumberofothernamesPicktheonethatmakesyouchillout

CommonStudentQuestionsTheseareactualquestionsthatrealstudentshaveaskedwhendoingthisexercise

CanIuseIDLENoyoushoulduseTerminalonmacOSandPowerShellonWindowsjustlikeIhavehereIfyoudonrsquotknowhowtousethosethenyoucangoreadtheappendix

HowdoyougetcolorsinyoureditorSaveyourfilefirstasapyfilesuchasex1pyThenyoursquollhavecolorwhenyoutype

IgetSyntaxErrorinvalidsyntaxwhenIrunex1pyYouareprobablytryingtorunPythonthentryingtotypePythonagainCloseyourTerminalstartitagainandrightawaytypeonlypython36ex1py

Igetcantopenfileex1py[Errno2]NosuchfileordirectoryYouneedtobeinthesamedirectoryasthefileyoucreatedMakesureyouusethecdcommandtogotherefirstForexampleifyousavedyourfileinlpthwex1pythenyouwoulddocdlpthwbeforetryingtorunpython36

ex1pyIfyoudonrsquotknowwhatanyofthatmeansthengothroughtheappendix

MyfiledoesnrsquotrunIjustgetthepromptbackwithnooutputYoumostlikelytookthecodeinmyex1pyfileliterallyandthoughtthatprint(HelloWorld)meanttotypeonlyHelloWorldintothefilewithouttheprintYourfilehastobeexactlylikemine

Exercise2CommentsandPoundCharacters

CommentsareveryimportantinyourprogramsTheyareusedtotellyouwhatsomethingdoesinEnglishandtheyareusedtodisablepartsofyourprogramifyouneedtoremovethemtemporarilyHerersquoshowyouusecommentsinPythonClickheretoviewcodeimage

ex2py

1Acommentthisissoyoucanreadyourprogramlater

2Anythingaftertheisignoredbypython

3

4print(Icouldhavecodelikethis)andthecommentafteris

ignored

5

6Youcanalsouseacommenttodisableorcommentoutcode

7print(Thiswontrun)

8

9print(Thiswillrun)

FromnowonIrsquomgoingtowritecodelikethisItisimportantforyoutounderstandthateverythingdoesnothavetobeliteralYourscreenandprogrammayvisuallylookdifferentbutwhatrsquosimportantisthetextyoutypeintothefileyoursquorewritinginyourtexteditorInfactIcouldworkwithanytexteditorandtheresultswouldbethesame

WhatYouShouldSee

Exercise2Session

$python36ex2py

Icouldhavecodelikethis

Thiswillrun

AgainIrsquomnotgoingtoshowyouscreenshotsofalltheTerminalspossibleYoushouldunderstandthattheprecedingisnotaliteraltranslationofwhatyouroutputshouldlooklikevisuallybutthetextbetweenthefirst$python36andlast$lineswillbewhatyoufocuson

StudyDrills

1Findoutifyouwererightaboutwhatthecharacterdoesandmakesureyouknowwhatitrsquoscalled(octothorpeorpoundcharacter)

2Takeyourex2pyfileandrevieweachlinegoingbackwardStartatthelastlineandcheckeachwordinreverseagainstwhatyoushouldhavetyped

3DidyoufindmoremistakesFixthem4ReadwhatyoutypedaboveoutloudincludingsayingeachcharacterbyitsnameDidyoufindmoremistakesFixthem

CommonStudentQuestionsAreyousureiscalledthepoundcharacterIcallittheoctothorpebecausethatistheonlynamethatnoonecountryusesandthatworksineverycountryEverycountrythinksitsnameforthisonecharacterisboththemostimportantwaytodoitandtheonlywayitrsquosdoneTomethisissimplyarroganceandreallyyrsquoallshouldjustchilloutandfocusonmoreimportantthingslikelearningtocode

Whydoestheinprint(Hithere)notgetignoredTheinthatcodeisinsideastringsoitwillbeputintothestringuntiltheendingcharacterishitPoundcharactersinstringsarejustconsideredcharactersnotcomments

HowdoIcommentoutmultiplelinesPutainfrontofeachoneIcanrsquotfigureouthowtotypeacharacteronmycountryrsquoskeyboardHowdoIdothatSomecountriesusetheALTkeyandcombinationsofotherkeystoprintcharactersforeigntotheirlanguageYoursquollhavetolookonlineinasearchenginetoseehowtotypeit

WhydoIhavetoreadcodebackwardItrsquosatricktomakeyourbrainnotattachmeaningtoeachpartofthecodeanddoingthatmakesyouprocesseachpieceexactlyThisisahandyerror-checkingtechnique

Exercise3NumbersandMath

EveryprogramminglanguagehassomekindofwayofdoingnumbersandmathDonotworryprogrammersfrequentlylieaboutbeingmathgeniuseswhentheyreallyarenrsquotIftheyweremathgeniusestheywouldbedoingmathnotwritingbuggywebframeworkssotheycandriveracecarsThisexercisehaslotsofmathsymbolsLetrsquosnamethemrightawaysoyouknowwhattheyarecalledAsyoutypethisoneinsaythenameWhensayingthemfeelsboringyoucanstopsayingthemHerearethenamesbull+plusbull-minusbullslashbullasteriskbullpercentbullltless-thanbullgtgreater-thanbulllt=less-than-equalbullgt=greater-than-equalNoticehowtheoperationsaremissingAfteryoutypeinthecodeforthisexercisegobackandfigureoutwhateachofthesedoesandcompletethetableForexample+doesadditionClickheretoviewcodeimage

ex3py

1print(Iwillnowcountmychickens)

2

3print(Hens25+306)

4print(Roosters100-2534)

5

6print(NowIwillcounttheeggs)

7

8print(3+2+1-5+42-14+6)

9

10print(Isittruethat3+2lt5-7)

11

12print(3+2lt5-7)

13

14print(Whatis3+23+2)

15print(Whatis5-75-7)

16

17print(OhthatswhyitsFalse)

18

19print(Howaboutsomemore)

20

21print(Isitgreater5gt-2)

22print(Isitgreaterorequal5gt=-2)

23print(Isitlessorequal5lt=-2)Makesureyoutypethis

exactlybeforeyourunitCompareeachlineofyourfiletomyfile

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise3Session

$python36ex3py

Iwillnowcountmychickens

Hens300

Roosters97

NowIwillcounttheeggs

675

Isittruethat3+2lt5-7

False

Whatis3+25

Whatis5-7-2

OhthatswhyitsFalse

Howaboutsomemore

IsitgreaterTrue

IsitgreaterorequalTrue

IsitlessorequalFalse

StudyDrills1Aboveeachlineusethetowriteacommenttoyourselfexplainingwhatthelinedoes

2RememberinExercise0whenyoustartedpython36Startpython36thiswayagainandusingthemathoperatorsusePythonasacalculator

3Findsomethingyouneedtocalculateandwriteanewpyfilethatdoesit

4Rewriteex3pytousefloatingpointnumberssoitrsquosmoreaccurate200isfloatingpoint

CommonStudentQuestionsWhyisthecharacteraldquomodulusrdquoandnotaldquopercentrdquoMostlythatrsquosjusthowthedesignerschosetousethatsymbolInnormalwritingyouarecorrecttoreaditasaldquopercentrdquoInprogrammingthiscalculationistypicallydonewithsimpledivisionandtheoperatorThemodulusisadifferentoperationthatjusthappenstousethesymbol

HowdoesworkAnotherwaytosayitisldquoXdividedbyYwithJ

remainingrdquoForexampleldquo100dividedby16with4remainingrdquoTheresultofistheJpartortheremainingpart

WhatistheorderofoperationsIntheUnitedStatesweuseanacronymcalledPEMDASwhichstandsforParenthesesExponentsMultiplicationDivisionAdditionSubtractionThatrsquostheorderPythonfollowsaswellThemistakepeoplemakewithPEMDASistothinkthisisastrictorderasinldquoDoPthenEthenMthenDthenAthenSrdquoTheactualorderisyoudothemultiplicationanddivision(MampD)inonestepfromlefttorightthenyoudotheadditionandsubtractioninonestepfromlefttorightSoyoucouldrewritePEMDASasPE(MampD)(AampS)

Exercise4VariablesandNames

NowyoucanprintthingswithprintandyoucandomathThenextstepistolearnaboutvariablesInprogrammingavariableisnothingmorethananameforsomethingsimilartohowmynameldquoZedrdquoisanameforldquothehumanwhowrotethisbookrdquoProgrammersusethesevariablenamestomaketheircodereadmorelikeEnglishandbecausetheyhavelousymemoriesIftheydidnrsquotusegoodnamesforthingsintheirsoftwaretheyrsquodgetlostwhentheytriedtoreadtheircodeagainIfyougetstuckwiththisexerciserememberthetricksyouhavebeentaughtsofaroffindingdifferencesandfocusingondetails1WriteacommentaboveeachlineexplainingtoyourselfinEnglishwhatitdoes

2Readyourpyfilebackward3Readyourpyfileoutloudsayingeventhecharacters

Clickheretoviewcodeimage

ex4py

1cars=100

2space_in_a_car=40

3drivers=30

4passengers=90

5cars_not_driven=cars-drivers

6cars_driven=drivers

7carpool_capacity=cars_drivenspace_in_a_car

8average_passengers_per_car=passengerscars_driven

9

10

11print(Therearecarscarsavailable)

12print(Thereareonlydriversdriversavailable)

13print(Therewillbecars_not_drivenemptycarstoday)

14print(Wecantransportcarpool_capacitypeopletoday)

15print(Wehavepassengerstocarpooltoday)

16print(Weneedtoputaboutaverage_passengers_per_car

17ineachcar)

WarningThe_inspace_in_a_cariscalledanunderscorecharacterFindouthowtotypeitifyoudonotalreadyknowWeusethischaracteralotto

putanimaginaryspacebetweenwordsinvariablenames

WhatYouShouldSeeClickheretoviewcodeimage

Exercise4Session

$python36ex4py

Thereare100carsavailable

Thereareonly30driversavailable

Therewillbe70emptycarstoday

Wecantransport1200peopletoday

Wehave90tocarpooltoday

Weneedtoputabout30ineachcar

StudyDrillsWhenIwrotethisprogramthefirsttimeIhadamistakeandPythontoldmeaboutitlikethisClickheretoviewcodeimage

Traceback(mostrecentcalllast)

Fileex4pyline8inltmodulegt

average_passengers_per_car=car_pool_capacitypassenger

NameErrornamecar_pool_capacityisnotdefined

ExplainthiserrorinyourownwordsMakesureyouuselinenumbersandexplainwhyHerearemorestudydrills1Iused40forspace_in_a_carbutisthatnecessaryWhathappensifitrsquosjust4

2Rememberthat40isafloatingpointnumberItrsquosjustanumberwithadecimalpointandyouneed40insteadofjust4sothatitisfloatingpoint

3Writecommentsaboveeachofthevariableassignments4Makesureyouknowwhat=iscalled(equals)andthatitspurposeistogivedata(numbersstringsetc)names(cars_drivenpassengers)

5Rememberthat_isanunderscorecharacter6Tryrunningpython36fromtheTerminalasacalculatorlikeyoudidbeforeandusevariablenamestodoyourcalculationsPopularvariablenamesincludeixandj

CommonStudentQuestions

CommonStudentQuestionsWhatisthedifferencebetween=(single-equal)and==(double-equal)The=(single-equal)assignsthevalueontherighttoavariableontheleftThe==(double-equal)testswhethertwothingshavethesamevalueYoursquolllearnaboutthisinExercise27

Canwewritex=100insteadofx=100YoucanbutitrsquosbadformYoushouldaddspacearoundoperatorslikethissothatitrsquoseasiertoread

WhatdoyoumeanbyldquoreadthefilebackwardrdquoVerysimpleImagineyouhaveafilewith16linesofcodeinitStartatline16andcompareittomyfileatline16Thendoitagainfor15andsoonuntilyoursquovereadthewholefilebackward

Whydidyouuse40forspace_in_a_carItismostlysoyoucanthenfindoutwhatafloatingpointnumberisandaskthisquestionSeetheStudyDrills

Exercise5MoreVariablesandPrinting

NowwersquolldoevenmoretypingofvariablesandprintingthemoutThistimewersquollusesomethingcalledaformatstringEverytimeyouput(double-quotes)aroundapieceoftextyouhavebeenmakingastringAstringishowyoumakesomethingthatyourprogrammightgivetoahumanYouprintstringssavestringstofilessendstringstowebserversamongmanyotherthingsStringsarereallyhandysointhisexerciseyouwilllearnhowtomakestringsthathavevariablesembeddedinthemYouembedvariablesinsideastringbyusingaspecialsequenceandthenputthevariableyouwantinsidethecharactersYoualsomuststartthestringwiththeletterfforldquoformatrdquoasinfHellosomevarThislittlefbeforethe(double-quote)andthecharacterstellPython3ldquoHeythisstringneedstobeformattedPutthesevariablesinthererdquoAsusualjusttypethisinevenifyoudonotunderstanditandmakeitexactlythesameClickheretoviewcodeimage

ex5py

1my_name=ZedAShaw

2my_age=35notalie

3my_height=74inches

4my_weight=180lbs

5my_eyes=Blue

6my_teeth=White

7my_hair=Brown

8

9print(fLetstalkaboutmy_name)

10print(fHesmy_heightinchestall)

11print(fHesmy_weightpoundsheavy)

12print(Actuallythatsnottooheavy)

13print(fHesgotmy_eyeseyesandmy_hairhair)

14print(fHisteethareusuallymy_teethdependingonthe

coffee)

15

16thislineistrickytrytogetitexactlyright

17total=my_age+my_height+my_weight

18print(fIfIaddmy_agemy_heightandmy_weightIget

total)

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise5Session

$python36ex5py

LetstalkaboutZedAShaw

Hes74inchestall

Hes180poundsheavy

Actuallythatsnottooheavy

HesgotBlueeyesandBrownhair

HisteethareusuallyWhitedependingonthecoffee

IfIadd3574and180Iget289

StudyDrills1Changeallthevariablessothereisnomy_infrontofeachoneMakesureyouchangethenameeverywherenotjustwhereyouused=tosetthem

2TrytowritesomevariablesthatconverttheinchesandpoundstocentimetersandkilogramsDonotjusttypeinthemeasurementsWorkoutthemathinPython

CommonStudentQuestionsCanImakeavariablelikethis1=ZedShawNo1isnotavalidvariablenameTheyneedtostartwithacharactersoa1wouldworkbut1willnot

HowcanIroundafloatingpointnumberYoucanusetheround()functionlikethisround(17333)

WhydoesthisnotmakesensetomeTrymakingthenumbersinthisscriptyourmeasurementsItrsquosweirdbuttalkingaboutyourselfwillmakeitseemmorerealAlsoyoursquorejuststartingoutsoitwonrsquotmaketoomuchsenseKeepgoingandmoreexerciseswillexplainitmore

Exercise6StringsandText

WhileyouhavebeenwritingstringsyoustilldonotknowwhattheydoInthisexercisewecreateabunchofvariableswithcomplexstringssoyoucanseewhattheyareforFirstanexplanationofstringsAstringisusuallyabitoftextyouwanttodisplaytosomeoneorldquoexportrdquooutoftheprogramyouarewritingPythonknowsyouwantsomethingtobeastringwhenyouputeither(double-quotes)or(single-quotes)aroundthetextYousawthismanytimeswithyouruseofprintwhenyouputthetextyouwanttogoinsidethestringinsideoraftertheprinttoprintthestringStringscancontainanynumberofvariablesthatareinyourPythonscriptRememberthatavariableisanylineofcodewhereyousetaname=(equal)toavalueInthecodeforthisexercisetypes_of_people=10createsavariablenamedtypes_of_peopleandsetsit=(equal)to10Youcanputthatinanystringwithtypes_of_peopleYoualsoseethatIhavetouseaspecialtypeofstringtoldquoformatrdquoitrsquoscalledanldquof-stringrdquoandlookslikethisClickheretoviewcodeimage

fsomestuffhereavariable

fsomeotherstuffanothervar

Pythonalsohasanotherkindofformattingusingtheformat()syntaxwhichyouseeonline17YoursquollseemeusethatsometimeswhenIwanttoapplyaformattoanalready-createdstringsuchasinaloopWersquollcoverthatmorelaterWewillnowtypeinawholebunchofstringsvariablesandformatsandprintthemWewillalsopracticeusingshortabbreviatedvariablenamesProgrammerslovesavingtimeatyourexpensebyusingannoyinglyshortandcrypticvariablenamessoletrsquosgetyoustartedreadingandwritingthemearlyonClickheretoviewcodeimage

ex6py

1types_of_people=10

2x=fTherearetypes_of_peopletypesofpeople

3

4binary=binary

5do_not=dont

6y=fThosewhoknowbinaryandthosewhodo_not

7

8print(x)

9print(y)

10

11print(fIsaidx)

12print(fIalsosaidy)

13

14hilarious=False

15joke_evaluation=Isntthatjokesofunny

16

17print(joke_evaluationformat(hilarious))

18

19w=Thisistheleftsideof

20e=astringwitharightside

21

22print(w+e)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise6Session

$python36ex6py

Thereare10typesofpeople

Thosewhoknowbinaryandthosewhodont

IsaidThereare10typesofpeople

IalsosaidThosewhoknowbinaryandthosewhodont

IsntthatjokesofunnyFalse

Thisistheleftsideofastringwitharightside

StudyDrills1Gothroughthisprogramandwriteacommentaboveeachlineexplainingit

2FindalltheplaceswhereastringisputinsideastringTherearefourplaces

3AreyousurethereareonlyfourplacesHowdoyouknowMaybeIlikelying

4Explainwhyaddingthetwostringswandewith+makesalongerstring

BreakIt

YouarenowatapointwhereyoucantrytobreakyourcodetoseewhathappensThinkofthisasagametodevisethemostcleverwaytobreakthecodeYoucanalsofindthesimplestwaytobreakitOnceyoubreakthecodeyouthenneedtofixitIfyouhaveafriendthenthetwoofyoucantrytobreakeachotherrsquoscodeandfixitGiveyourfriendyourex6pyfilesotheycanbreaksomethingThenyoutrytofindtheirerrorandfixitHavefunwiththisandrememberthatifyouwrotethiscodeonceyoucandoitagainIfyoutakeyourdamagetoofaryoucanalwaystypeitinagainforextrapractice

CommonStudentQuestionsWhydoyouput(single-quotes)aroundsomestringsandnotothersMostlyitrsquosbecauseofstylebutIrsquolluseasingle-quoteinsideastringthathasdouble-quotesLookatlines6and15toseehowIrsquomdoingthat

Ifyouthoughtthejokewasfunnycouldyouwritehilarious=TrueYesandyoursquolllearnmoreaboutthesebooleanvaluesinExercise27

Exercise7MorePrinting

NowwearegoingtodoabunchofexerciseswhereyoujusttypecodeinandmakeitrunIwonrsquotbeexplainingthisexercisebecauseitismoreofthesameThepurposeistobuildupyourchopsSeeyouinafewexercisesanddonotskipDonotpasteClickheretoviewcodeimage

ex7py

1print(Maryhadalittlelamb)

2print(Itsfleecewaswhiteasformat(snow))

3print(AndeverywherethatMarywent)

4print(10)whatdthatdo

5

6end1=C

7end2=h

8end3=e

9end4=e

10end5=s

11end6=e

12end7=B

13end8=u

14end9=r

15end10=g

16end11=e

17end12=r

18

19watchthatcommaattheendtryremovingittoseewhat

happens

20print(end1+end2+end3+end4+end5+end6end=)

21print(end7+end8+end9+end10+end11+end12)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise7Session

$python36ex7py

Maryhadalittlelamb

Itsfleecewaswhiteassnow

AndeverywherethatMarywent

CheeseBurger

StudyDrillsForthesenextfewexercisesyouwillhavetheexactsameStudyDrills

1Gobackthroughandwriteacommentonwhateachlinedoes2Readeachonebackwardoroutloudtofindyourerrors3Fromnowonwhenyoumakemistakeswritedownonapieceofpaperwhatkindofmistakeyoumade

4Whenyougotothenextexerciselookatthemistakesyouhavemadeandtrynottomaketheminthisnewone

5RememberthateveryonemakesmistakesProgrammersarelikemagicianswhofooleveryoneintothinkingtheyareperfectandneverwrongbutitrsquosallanactTheymakemistakesallthetime

BreakItDidyouhavefunbreakingthecodeinExercise6FromnowonyoursquoregoingtobreakallthecodeyouwriteorafriendrsquoscodeIwonrsquothaveaBreakItsectionexplicitlyineveryexercisebutIwilldothisinalmosteveryvideoYourgoalistofindasmanydifferentwaystobreakyourcodeuntilyougettiredorexhaustallpossibilitiesInsomeexercisesImightpointoutaspecificcommonwaypeoplebreakthatexercisersquoscodebutotherwiseconsiderthisastandingordertoalwaysbreakit

CommonStudentQuestionsWhyareyouusingthevariablenamedsnowThatrsquosactuallynotavariableitisjustastringwiththewordsnowinitAvariablewouldnrsquothavethesingle-quotesaroundit

IsitnormaltowriteanEnglishcommentforeverylineofcodelikeyousaytodoinStudyDrill1Noyouwritecommentsonlytoexplaindifficult-to-understandcodeorwhyyoudidsomethingWhyisusuallymuchmoreimportantandthenyoutrytowritethecodesothatitexplainshowsomethingisbeingdoneonitsownHoweversometimesyouhavetowritesuchnastycodetosolveaproblemthatitdoesneedacommentoneverylineInthiscaseitrsquosstrictlyforyoutopracticetranslatingcodetoEnglish

CanIusesingle-quotesordouble-quotestomakeastringordo

theydodifferentthingsInPythoneitherwaytomakeastringisacceptablealthoughtypicallyyoursquollusesingle-quotesforanyshortstringslikeaorsnow

Exercise8PrintingPrinting

WewillnowseehowtodoamorecomplicatedformattingofastringThiscodelookscomplexbutifyoudoyourcommentsaboveeachlineandbreakeachthingdowntoitspartsyoursquollunderstanditClickheretoviewcodeimage

ex8py

1formatter=

2

3print(formatterformat(1234))

4print(formatterformat(onetwothreefour))

5print(formatterformat(TrueFalseFalseTrue))

6print(formatterformat(formatterformatterformatter

formatter))

7print(formatterformat(

8Tryyour

9Owntexthere

10Maybeapoem

11Orasongaboutfear

12))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise8Session

$python36ex8py

1234

onetwothreefour

TrueFalseFalseTrue

TryyourOwntexthereMaybeapoemOrasongaboutfearInthis

exerciseIrsquomusingsomethingcalledafunctiontoturntheformatter

variableintootherstringsWhenyouseemewrite

formatterformat()Irsquomtellingpythontodothefollowing1Take

theformatterstringdefinedonline1

2Callitsformatfunctionwhichissimilartotellingittodoacommandlinecommandnamedformat

3PasstoformatfourargumentswhichmatchupwiththefoursintheformattervariableThisislikepassingargumentstothecommandlinecommandformat

4TheresultofcallingformatonformatterisanewstringthathasthereplacedwiththefourvariablesThisiswhatprintisnowprintingout

ThatrsquosalotfortheeighthexercisesowhatIwantyoutodoisconsiderthisabrainteaserItrsquosalrightifyoudonrsquotreallyunderstandwhatrsquosgoingonbecausetherestofthebookwillslowlymakethisclearAtthispointtrytostudythisandseewhatrsquosgoingonthenmoveontothenextexercise

StudyDrillsDoyourcheckswritedownyourmistakesandtrynottomakethesamemistakesonthenextexerciseInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIhavetoputquotesaroundonebutnotaroundTrueorFalsePythonrecognizesTrueandFalseaskeywordsrepresentingtheconceptoftrueandfalseIfyouputquotesaroundthemthentheyareturnedintostringsandwonrsquotworkYoursquolllearnmoreabouthowtheseworkinExercise27

CanIuseIDLEtorunthisNoyoushouldlearntousethecommandlineItisessentialtolearningprogrammingandisagoodplacetostartifyouwanttolearnaboutprogrammingIDLEwillfailforyouwhenyougetfurtherinthebook

Exercise9PrintingPrintingPrinting

BynowyoushouldrealizethepatternforthisbookistousemorethanoneexercisetoteachyousomethingnewIstartwithcodethatyoumightnotunderstandthenmoreexercisesexplaintheconceptIfyoudonrsquotunderstandsomethingnowyouwilllaterasyoucompletemoreexercisesWritedownwhatyoudonrsquotunderstandandkeepgoingClickheretoviewcodeimage

ex9py

1Heressomenewstrangestuffremembertypeitexactly

2

3days=MonTueWedThuFriSatSun

4months=JannFebnMarnAprnMaynJunnJulnAug

5

6print(Herearethedaysdays)

7print(Herearethemonthsmonths)

8

9print(

10Theressomethinggoingonhere

11Withthethreedouble-quotes

12Wellbeabletotypeasmuchaswelike

13Even4linesifwewantor5or6

14)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise9Session

$python36ex9py

HerearethedaysMonTueWedThuFriSatSun

HerearethemonthsJan

Feb

Mar

Apr

May

Jun

Jul

Aug

Theressomethinggoingonhere

Withthethreedouble-quotes

Wellbeabletotypeasmuchaswelike

Even4linesifwewantor5or6

StudyDrillsCheckyourworkwritedownyourmistakestrynottomakethemonthenextexerciseAreyoubreakingyourcodeandthenfixingitInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIgetanerrorwhenIputspacesbetweenthethreedouble-quotesYouhavetotypethemlikeandnotmeaningwithnospacesbetweeneachone

WhatifIwantedtostartthemonthsonanewlineYousimplystartthestringwithnlikethisClickheretoviewcodeimagenJannFebnMarnAprnMaynJunnJulnAug

IsitbadthatmyerrorsarealwaysspellingmistakesMostprogrammingerrorsinthebeginning(andevenlater)aresimplespellingmistakestyposorgettingsimplethingsoutoforder

Exercise10WhatWasThat

InExercise9IthrewyousomenewstuffjusttokeepyouonyourtoesIshowedyoutwowaystomakeastringthatgoesacrossmultiplelinesInthefirstwayIputthecharactersn(backslashn)betweenthenamesofthemonthsThesetwocharactersputanewlinecharacterintothestringatthatpointThis(backslash)characterencodesdifficult-to-typecharactersintoastringTherearevariousescapesequencesavailablefordifferentcharactersyoumightwanttouseWersquolltryafewofthesesequencessoyoucanseewhatImeanAnimportantescapesequenceistoescapeasingle-quote()ordouble-quote()Imagineyouhaveastringthatusesdouble-quotesandyouwanttoputadouble-quoteinsidethestringIfyouwriteIunderstandjoethenPythonwillgetconfusedbecauseitwillthinkthedouble-quotesaroundunderstandactuallyendsthestringYouneedawaytotellPythonthatthedouble-quoteinsidethestringisnrsquotarealdouble-quoteTosolvethisproblemyouescapedouble-quotesandsingle-quotessoPythonknowstoincludetheminthestringHerersquosanexampleClickheretoviewcodeimage

Iam62tallescapedoublendashquoteinsidestring

Iam62tallescapesinglendashquoteinsidestringThesecond

wayisbyusingtriple-quoteswhichisjustandworkslikea

stringbutyoualsocanputasmanylinesoftextasyouwantuntil

youtypeagainWersquollalsoplaywiththese

Clickheretoviewcodeimage

ex10py

1tabby_cat=tImtabbedin

2persian_cat=Imsplitnonaline

3backslash_cat=Imacat

4

5fat_cat=

6Illdoalist

7tCatfood

8tFishies

9tCatnipntGrass

10

11

12print(tabby_cat)

13print(persian_cat)

14print(backslash_cat)

15print(fat_cat)

WhatYouShouldSeeLookforthetabcharactersthatyoumadeInthisexercisethespacingisimportanttogetright

$pythonex10py

Imtabbedin

Imsplit

onaline

Imacat

Illdoalist

Catfood

Fishies

Catnip

Grass

EscapeSequencesThisisalloftheescapesequencesPythonsupportsYoumaynotusemanyofthesebutmemorizetheirformatandwhattheydoanywayTrythemoutinsomestringstoseeifyoucanmakethemwork

StudyDrills1Memorizealltheescapesequencesbyputtingthemonflashcards2Use(triple-single-quote)insteadCanyouseewhyyoumightusethatinsteadof

3Combineescapesequencesandformatstringstocreateamorecomplexformat

CommonStudentQuestionsIstillhavenrsquotcompletelyfiguredoutthelastexerciseShouldIcontinueYeskeepgoingInsteadofstoppingtakenoteslistingthingsyoudonrsquotunderstandforeachexercisePeriodicallygothroughyournotesandseeifyoucanfigurethesethingsoutafteryoursquovecompletedmoreexercisesSometimesthoughyoumayneedtogobackafewexercisesanddothemagain

WhatmakesspecialcomparedtotheotheronesItrsquossimplythewayyouwouldwriteoutonebackslash()characterThinkaboutwhyyouwouldneedthis

WhenIwriteornitdoesnrsquotworkThatrsquosbecauseyouareusingaforward-slash()andnotabackslash()Theyaredifferentcharactersthatdoverydifferentthings

IdonrsquotgetStudyDrill3WhatdoyoumeanbyldquocombinerdquoescapesequencesandformatsOneconceptIneedyoutounderstandisthateachoftheseexercisescanbecombinedtosolveproblemsTakewhatyouknowaboutformatstringsandwritesomenewcodethatusesformatstringsandtheescapesequencesfromthisexercise

WhatrsquosbetterorItrsquosentirelybasedonstyleGowiththe(triple-single-quote)stylefornowbutbereadytouseeitherdependingonwhatfeelsbestorwhateveryoneelseisdoing

Exercise11AskingQuestions

NowitistimetopickupthepaceYouaredoingalotofprintingtogetyoufamiliarwithtypingsimplethingsbutthosesimplethingsarefairlyboringWhatwewanttodonowisgetdataintoyourprogramsThisisalittletrickybecauseyouhavetolearntodotwothingsthatmaynotmakesenserightawaybuttrustmeanddoitanywayItwillmakesenseinafewexercisesMostofwhatsoftwaredoesisthefollowing1Takessomekindofinputfromaperson

2Changesit3Printsoutsomethingtoshowhowitchanged

SofaryouhavebeenprintingstringsbutyouhavenrsquotbeenabletogetanyinputfromapersonYoumaynotevenknowwhatldquoinputrdquomeansbuttypethiscodeinanywayandmakeitexactlythesameInthenextexercisewersquolldomoretoexplaininputClickheretoviewcodeimage

ex11py

1print(Howoldareyouend=)

2age=input()

3print(Howtallareyouend=)

4height=input()

5print(Howmuchdoyouweighend=)

6weight=input()

7

8print(fSoyoureageoldheighttallandweight

heavy)

WarningWeputanend=attheendofeachprintlineThistellsprinttonotendthelinewithanewlinecharacterandgotothenextline

WhatYouShouldSeeClickheretoviewcodeimage

Exercise11Session

$python36ex11py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1GoonlineandfindoutwhatPythonrsquosinputdoes2CanyoufindotherwaystouseitTrysomeofthesamplesyoufind3Writeanotherldquoformrdquolikethistoasksomeotherquestions

CommonStudentQuestionsHowdoIgetanumberfromsomeonesoIcandomathThatrsquosalittleadvancedbuttryx=int(input())whichgetsthenumberasastringfrominput()thenconvertsittoanintegerusingint()

Iputmyheightintorawinputlikethisinput(62)butitdoesnrsquotworkDonrsquotputyourheightintheretypeitdirectlyintoyourTerminalFirstgobackandmakethecodeexactlylikemineNextrunthescriptandwhenitpausestypeyourheightinatyourkeyboardThatrsquosallthereistoit

Exercise12PromptingPeople

Whenyoutypedinput()youweretypingthe(and)characterswhichareparenthesischaractersThisissimilartowhenyouusedthemtodoaformatwithextravariablesasinfxyForinputyoucanalsoputinaprompttoshowtoapersonsoheknowswhattotypePutastringthatyouwantforthepromptinsidethe()sothatitlookslikethis

y=input(Name)

ThispromptstheuserwithldquoNamerdquoandputstheresultintothevariableyThisishowyouasksomeoneaquestionandgettheanswerThismeanswecancompletelyrewriteourpreviousexerciseusingjustinputtodoallthepromptingClickheretoviewcodeimage

ex12py

1age=input(Howoldareyou)

2height=input(Howtallareyou)

3weight=input(Howmuchdoyouweigh)

4

5print(fSoyoureageoldheighttallandweight

heavy)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise12Session

$python36ex12py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1InTerminalwhereyounormallyrunpython36torunyourscriptstypepydocinputReadwhatitsaysIfyoursquoreonWindowstry

python36-mpydocinputinstead2Getoutofpydocbytypingqtoquit3Lookonlineforwhatthepydoccommanddoes4UsepydoctoalsoreadaboutopenfileosandsysItrsquosalrightifyoudonotunderstandthosejustreadthroughandtakenotesaboutinterestingthings

CommonStudentQuestionsHowcomeIgetSyntaxErrorinvalidsyntaxwheneverIrunpydocYouarenrsquotrunningpydocfromthecommandlineyoursquoreprobablyrunningitfrominsidepython36Exitoutofpython36first

WhydoesmypydocnotpauselikeyoursdoesSometimesifthehelpdocumentisshortenoughtofitononescreenthenpydocwilljustprintit

WhenIrunpydocIgetmoreisnotrecognizedasaninternalSomeversionsofWindowsdonothavethatcommandwhichmeanspydocisbrokenforyouYoucanskipthisStudyDrillandjustsearchonlineforPythondocumentationwhenyouneedit

WhycanrsquotIdoprint(Howoldareyouinput())Youcanbutthentheresultofcallinginput()isneversavedtoavariableanditrsquollworkinastrangewayTrythisandthentrytoprintoutwhatyoutypeSeeifyoucandebugwhythisisnrsquotworking

Exercise13ParametersUnpackingVariables

Inthisexercisewewillcoveronemoreinputmethodyoucanusetopassvariablestoascript(scriptbeinganothernameforyourpyfiles)Youknowhowyoutypepython36ex13pytoruntheex13pyfileWelltheex13pypartofthecommandiscalledanargumentWhatwersquolldonowiswriteascriptthatalsoacceptsargumentsTypethisprogramandIrsquollexplainitindetailClickheretoviewcodeimage

ex13py

1fromsysimportargv

2readtheWYSSsectionforhowtorunthis

3scriptfirstsecondthird=argv

4

5print(Thescriptiscalledscript)

6print(Yourfirstvariableisfirst)

7print(Yoursecondvariableissecond)

8print(Yourthirdvariableisthird)

Online1wehavewhatrsquoscalledanimportThisishowyouaddfeaturestoyourscriptfromthePythonfeaturesetRatherthangiveyouallthefeaturesatoncePythonasksyoutosaywhatyouplantouseThiskeepsyourprogramssmallbutitalsoactsasdocumentationforotherprogrammerswhoreadyourcodelaterTheargvistheargumentvariableaverystandardnameinprogrammingthatyouwillfindusedinmanyotherlanguagesThisvariableholdstheargumentsyoupasstoyourPythonscriptwhenyourunitIntheexercisesyouwillgettoplaywiththismoreandseewhathappensLine3unpacksargvsothatratherthanholdingalltheargumentsitgetsassignedtofourvariablesyoucanworkwithscriptfirstsecondandthirdThismaylookstrangebutldquounpackrdquoisprobablythebestwordtodescribewhatitdoesItjustsaysldquoTakewhateverisinargvunpackitandassignittoallofthesevariablesontheleftinorderrdquoAfterthatwejustprintthemoutlikenormal

HoldUpFeaturesHaveAnotherName

Icallthemldquofeaturesrdquohere(theselittlethingsyouimporttomakeyourPythonprogramdomore)butnobodyelsecallsthemfeaturesIjustusedthatnamebecauseIneededtotrickyouintolearningwhattheyarewithoutjargonBeforeyoucancontinueyouneedtolearntheirrealnamemodulesFromnowonwewillbecallingtheseldquofeaturesrdquothatweimportmodulesIrsquollsaythingslikeldquoYouwanttoimportthesysmodulerdquoTheyarealsocalledldquolibrariesrdquobyotherprogrammersbutletrsquosjuststickwithmodules

WhatYouShouldSee

WarningPayattentionYouhavebeenrunningpythonscriptswithoutcommandlineargumentsIfyoutypeonlypython36ex13pyyouaredoingitwrongPaycloseattentiontohowIrunitThisappliesanytimeyouseeargvbeingused

Runtheprogramlikethis(andyoumustpassthreecommandlinearguments)Clickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd3rd

Thescriptiscalledex13py

Yourfirstvariableisfirst

Yoursecondvariableis2nd

Yourthirdvariableis3rd

ThisiswhatyoushouldseewhenyoudoafewdifferentrunswithdifferentargumentsClickheretoviewcodeimage

Exercise13Session

$python36ex13pystuffthingsthat

Thescriptiscalledex13py

Yourfirstvariableisstuff

Yoursecondvariableisthings

Yourthirdvariableisthat

$

$python36ex13pyappleorangegrapefruit

Thescriptiscalledex13py

Yourfirstvariableisapple

Yoursecondvariableisorange

Yourthirdvariableisgrapefruit

Youcanactuallyreplacefirst2ndand3rdwithanythreethingsyouwantIfyoudonotrunitcorrectlythenyouwillgetanerrorlikethisClickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd

Traceback(mostrecentcalllast)

Fileex13pyline3inltmodulegt

scriptfirstsecondthird=argv

ValueErrornotenoughvaluestounpack(expected4got3)

Thishappenswhenyoudonotputenoughargumentsonthecommandwhenyourunit(inthiscasejustfirst2nd)NoticethatwhenIrunitIgiveitfirst2ndwhichcausedittogiveanerroraboutldquoneedmorethan3valuestounpackrdquotellingyouthatyoudidnrsquotgiveitenoughparameters

StudyDrills1TrygivingfewerthanthreeargumentstoyourscriptSeethaterroryougetSeeifyoucanexplainit

2WriteascriptthathasfewerargumentsandonethathasmoreMakesureyougivetheunpackedvariablesgoodnames

3CombineinputwithargvtomakeascriptthatgetsmoreinputfromauserDonrsquotoverthinkitJustuseargvtogetsomethingandinputtogetsomethingelsefromtheuser

4RememberthatmodulesgiveyoufeaturesModulesModulesRememberthisbecausewersquollneeditlater

CommonStudentQuestionsWhenIrunitIgetValueErrorneedmorethan1valuetounpackRememberthatanimportantskillispayingattentiontodetailsIfyoulookattheWhatYouShouldSeesectionyouseethatIrunthescriptwithparametersonthecommandlineYoushouldreplicatehowIranitexactly

Whatrsquosthedifferencebetweenargvandinput()ThedifferencehastodowithwheretheuserisrequiredtogiveinputIftheygiveyourscriptinputsonthecommandlinethenyouuseargvIfyouwantthemtoinputusingthekeyboardwhilethescriptisrunningthenuseinput()

ArethecommandlineargumentsstringsYestheycomeinasstringsevenifyoutypednumbersonthecommandlineUseint()toconvertthemlikewithint(input())

HowdoyouusethecommandlineYoushouldhavelearnedtouseitveryquicklyandfluentlybynowbutifyouneedtolearnitatthisstagethenreadtheappendix

Icanrsquotcombineargvwithinput()DonrsquotoverthinkitJustslaptwolinesattheendofthisscriptthatuseinput()togetsomethingandthenprintitFromthatstartplayingwithmorewaystousebothinthesamescript

WhycanrsquotIdothisinput()=xBecausethatrsquosbackwardtohowitshouldworkDoitthewayIdoitanditrsquollwork

Exercise14PromptingandPassing

LetrsquosdooneexercisethatusesargvandinputtogethertoasktheusersomethingspecificYouwillneedthisforthenextexercisewhereyoulearntoreadandwritefilesInthisexercisewersquolluseinputslightlydifferentlybyhavingitprintasimplegtpromptThisissimilartogameslikeZorkorAdventureClickheretoviewcodeimage

ex14py

1fromsysimportargv

2

3scriptuser_name=argv

4prompt=gt

5

6print(fHiuser_nameImthescriptscript)

7print(Idliketoaskyouafewquestions)

8print(fDoyoulikemeuser_name)

9likes=input(prompt)

10

11print(fWheredoyouliveuser_name)

12lives=input(prompt)

13

14print(Whatkindofcomputerdoyouhave)

15computer=input(prompt)

16

17print(f

18Alrightsoyousaidlikesaboutlikingme

19YouliveinlivesNotsurewherethatis

20AndyouhaveacomputercomputerNice

21)Wemakeavariablepromptthatissettothepromptwe

wantandwegivethattoinputinsteadoftypingitoverandover

Nowifwewanttomakethepromptsomethingelsewejustchangeit

inthisonespotandrerunthescriptVeryhandy

WhatYouShouldSeeWhenyourunthisrememberthatyouhavetogivethescriptyournamefortheargvargumentsClickheretoviewcodeimage

Exercise14Session

$python36ex14pyzed

HizedImtheex14pyscript

Idliketoaskyouafewquestions

Doyoulikemezed

gtYes

Wheredoyoulivezed

gtSanFrancisco

Whatkindofcomputerdoyouhave

gtTandy1000

AlrightsoyousaidYesaboutlikingme

YouliveinSanFranciscoNotsurewherethatis

AndyouhaveaTandy1000computerNice

StudyDrills1FindoutwhatthegamesZorkandAdventurewereTrytofindcopiesandplaythem

2Changethepromptvariabletosomethingelseentirely3Addanotherargumentanduseitinyourscriptthesamewayyoudidinthepreviousexercisewithfirstsecond=ARGV

4MakesureyouunderstandhowIcombinedastylemultilinestringwiththeformatactivatorasthelastprint

CommonStudentQuestionsIgetSyntaxErrorinvalidsyntaxwhenIrunthisscriptAgainyouhavetorunitrightonthecommandlinenotinsidePythonIfyoutypepython36andthentrytotypepython36ex14pyZeditwillfailbecauseyouarerunningPythoninsidePythonCloseyourwindowandthenjusttypepython36ex14pyZed

IdonrsquotunderstandwhatyoumeanbychangingthepromptSeethevariableprompt=gtChangethattohaveadifferentvalueYouknowthisitrsquosjustastringandyoursquovedone13exercisesmakingthemsotakethetimetofigureitout

IgettheerrorValueErrorneedmorethan1valuetounpackRememberwhenIsaidyouneedtolookattheWhatYouShouldSeesectionandreplicatewhatIdidYouneedtodothesamethinghereandfocusonhowItypethecommandinandwhyIhaveacommandlineargument

HowcanIrunthisfromIDLEDonrsquotuseIDLECanIusedouble-quotesforthepromptvariableYoutotallycanGoaheadandtrythat

YouhaveaTandycomputerIdidwhenIwaslittleIgetNameErrornamepromptisnotdefinedwhenIrunitYoueitherspelledthenameofthepromptvariablewrongorforgotthatlineGobackandcompareeachlineofcodetominestartingatthebottomofthescriptandworkinguptothetopAnytimeyouseethiserroritmeansyouspelledsomethingwrongorforgottocreatethevariable

Exercise15ReadingFiles

YouknowhowtogetinputfromauserwithinputorargvNowyouwilllearnaboutreadingfromafileYoumayhavetoplaywiththisexercisethemosttounderstandwhatrsquosgoingonsodotheexercisecarefullyandrememberyourchecksWorkingwithfilesisaneasywaytoeraseyourworkifyouarenotcarefulThisexerciseinvolveswritingtwofilesOneistheusualex15pyfilethatyouwillrunbuttheotherisnamedex15_sampletxtThissecondfileisnrsquotascriptbutaplaintextfilewersquollbereadinginourscriptHerearethecontentsofthatfileClickheretoviewcodeimage

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

WhatwewanttodoisopenthatfileinourscriptandprintitoutHoweverwedonotwanttojusthardcodethenameex15_sampletxtintoourscriptldquoHardcodingrdquomeansputtingsomebitofinformationthatshouldcomefromtheuserasastringdirectlyinoursourcecodeThatrsquosbadbecausewewantittoloadotherfileslaterThesolutionistouseargvorinputtoasktheuserwhatfiletoopeninsteadofhardcodingthefilersquosnameClickheretoviewcodeimage

ex15py

1fromsysimportargv

2

3scriptfilename=argv

4

5txt=open(filename)

6

7print(fHeresyourfilefilename)

8print(txtread())

9

10print(Typethefilenameagain)

11file_again=input(gt)

12

13txt_again=open(file_again)

14

15print(txt_againread())Afewfancythingsaregoingoninthis

filesoletrsquosbreakitdownrealquicklybullLines1ndash3useargvto

getafilenameNextwehaveline5whereweuseanewcommand

openRightnowrunpydocopenandreadtheinstructionsNotice

howlikeyourownscriptsandinputittakesaparameterand

returnsavalueyoucansettoyourownvariableYoujustopeneda

file

bullLine7printsalittlemessagebutonline8wehavesomethingverynewandexcitingWecallafunctionontxtnamedreadWhatyougetbackfromopenisafileanditalsohascommandsyoucangiveitYougiveafileacommandbyusingthe(dotorperiod)thenameofthecommandandparametersjustlikewithopenandinputThedifferenceisthattxtread()saysldquoHeytxtDoyourreadcommandwithnoparametersrdquo

TheremainderofthefileismoreofthesamebutwersquollleavetheanalysistoyouintheStudyDrills

WhatYouShouldSee

WarningPayattentionIsaidpayattentionYouhavebeenrunningscriptswithjustthenameofthescriptbutnowthatyouareusingargvyouhavetoaddargumentsLookattheveryfirstlineoftheexamplebelowandyouwillseeIdopythonex15pyex15_sampletxttorunitSeetheextraargumentex15_sampletxtaftertheex15pyscriptnameIfyoudonottypethatyouwillgetanerrorsopayattention

Imadeafilecalledex15_sampletxtandranmyscriptClickheretoviewcodeimage

Exercise15Session

$python36ex15pyex15_sampletxt

Heresyourfileex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

Typethefilenameagain

gtex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

StudyDrillsThisisabigjumpsobesureyoudothisStudyDrillasbestyoucanbeforemovingon

1AboveeachlinecommentoutinEnglishwhatthatlinedoes2IfyouarenotsureasksomeoneforhelporsearchonlineManytimessearchingforldquopython36THINGrdquowillfindanswerstowhatthatTHINGdoesinPythonTrysearchingforldquopython36openrdquo

3IusedthewordldquocommandsrdquoherebutcommandsarealsocalledldquofunctionsrdquoandldquomethodsrdquoYouwilllearnaboutfunctionsandmethodslaterinthebook

4Getridoflines10ndash15whereyouuseinputandrunthescriptagain5UseonlyinputandtrythescriptthatwayWhyisonewayofgettingthefilenamebetterthananother

6Startpython36tostartthepython36shellanduseopenfromthepromptjustlikeinthisprogramNoticehowyoucanopenfilesandrunreadonthemfromwithinpython36

7Haveyourscriptalsocallclose()onthetxtandtxt_againvariablesItrsquosimportanttoclosefileswhenyouaredonewiththem

CommonStudentQuestionsDoestxt=open(filename)returnthecontentsofthefileNoitdoesnrsquotItactuallymakessomethingcalledafileobjectYoucanthinkofafilelikeanoldtapedrivethatyousawonmainframecomputersinthe1950sorevenlikeaDVDplayerfromtodayYoucanmovearoundinsidethemandthenldquoreadrdquothembuttheDVDplayerisnottheDVDthesamewaythefileobjectisnotthefilersquoscontents

IcanrsquottypecodeintoTerminalPowerShelllikeyousayinStudyDrill7Firstfromthecommandlinejusttypepython36andpressEnterNowyouareinpython36aswersquovedoneafewothertimesThenyoucantypeincodeandPythonwillrunitinlittlepiecesPlaywiththatTogetoutofittypequit()andhitEnter

WhyistherenoerrorwhenweopenthefiletwicePythonwillnotrestrictyoufromopeningafilemorethanonceandsometimesthisisnecessary

WhatdoesfromsysimportargvmeanFornowjustunderstandthatsysisapackageandthisphrasejustsaystogettheargvfeaturefromthatpackageYoursquolllearnmoreabouttheselater

Iputthenameofthefileinasscriptex15_sampletxt=argvbutitdoesnrsquotworkNothatrsquosnothowyoudoitMakethecodeexactlylikeminethenrunitfromthecommandlinetheexactsamewayIdoYoudonrsquotputthenamesoffilesinyouletPythonputthenamein

Exercise16ReadingandWritingFiles

IfyoudidtheStudyDrillsfromthelastexerciseyoushouldhaveseenallsortsofcommands(methodsfunctions)youcangivetofilesHerersquosthelistofcommandsIwantyoutorememberbullcloseClosesthefileLikeFile-gtSaveinyoureditor

bullreadReadsthecontentsofthefileYoucanassigntheresulttoavariable

bullreadlineReadsjustonelineofatextfilebulltruncateEmptiesthefileWatchoutifyoucareaboutthefilebullwrite(stuff)Writesldquostuffrdquotothefilebullseek(0)Movesthereadwritelocationtothebeginningofthefile

OnewaytorememberwhateachofthesedoesistothinkofavinylrecordcassettetapeVHStapeDVDorCDplayerIntheearlydaysofcomputersdatawasstoredoneachofthesekindsofmediasomanyofthefileoperationsstillresembleastoragesystemthatislinearTapeandDVDdrivesneedtoldquoseekrdquoaspecificspotandthenyoucanreadorwriteatthatspotTodaywehaveoperatingsystemsandstoragemediathatblurthelinesbetweenrandomaccessmemoryanddiskdrivesbutwestillusetheolderideaofalineartapewithareadwriteheadthatmustbemovedFornowthesearetheimportantcommandsyouneedtoknowSomeofthemtakeparametersbutwedonotreallycareaboutthatYouonlyneedtorememberthatwritetakesaparameterofastringyouwanttowritetothefileLetrsquosusesomeofthistomakeasimplelittletexteditorClickheretoviewcodeimage

ex16py

1fromsysimportargv

2

3scriptfilename=argv

4

5print(fWeregoingtoerasefilename)

6print(IfyoudontwantthathitCTRL-C(^C))

7print(IfyoudowantthathitRETURN)

8

9input()

10

11print(Openingthefile)

12target=open(filenamew)

13

14print(TruncatingthefileGoodbye)

15targettruncate()

16

17print(NowImgoingtoaskyouforthreelines)

18

19line1=input(line1)

20line2=input(line2)

21line3=input(line3)

22

23print(Imgoingtowritethesetothefile)

24

25targetwrite(line1)

26targetwrite(n)

27targetwrite(line2)

28targetwrite(n)

29targetwrite(line3)

30targetwrite(n)

31

32print(Andfinallywecloseit)

33targetclose()

ThatrsquosalargefileprobablythelargestyouhavetypedinSogoslowdoyourchecksandmakeitrunOnetrickistogetbitsofitrunningatatimeGetlines1ndash8runningthenfivemorethenafewmoreuntilitrsquosalldoneandrunning

WhatYouShouldSeeThereareactuallytwothingsyouwillseeFirsttheoutputofyournewscriptClickheretoviewcodeimage

Exercise16Session

$python36ex16pytesttxt

Weregoingtoerasetesttxt

IfyoudontwantthathitCTRL-C(^C)

IfyoudowantthathitRETURN

Openingthefile

TruncatingthefileGoodbye

NowImgoingtoaskyouforthreelines

line1Maryhadalittlelamb

line2Itsfleecewaswhiteassnow

line3Itwasalsotasty

Imgoingtowritethesetothefile

Andfinallywecloseit

Nowopenupthefileyoumade(inmycasetesttxt)inyoureditorandcheckitoutNeatright

StudyDrills1IfyoudonotunderstandthisgobackthroughandusethecommenttricktogetitsquaredawayinyourmindOnesimpleEnglishcommentaboveeachlinewillhelpyouunderstandoratleastletyouknowwhatyouneedtoresearchmore

2Writeascriptsimilartothelastexercisethatusesreadandargvtoreadthefileyoujustcreated

3TherersquostoomuchrepetitioninthisfileUsestringsformatsandescapestoprintoutline1line2andline3withjustonetargetwrite()commandinsteadofsix

4FindoutwhywehadtopassawasanextraparametertoopenHintopentriestobesafebymakingyouexplicitlysayyouwanttowriteafile

5Ifyouopenthefilewithwmodethendoyoureallyneedthetargettruncate()ReadthedocumentationforPythonrsquosopenfunctionandseeifthatrsquostrue

CommonStudentQuestionsIsthetruncate()necessarywiththewparameterSeeStudyDrillsnumber5

WhatdoeswmeanItrsquosreallyjustastringwithacharacterinitforthekindofmodeforthefileIfyouusewthenyoursquoresayingldquoopenthisfileinlsquowritersquomoderdquothusthewcharacterTherersquosalsorforldquoreadrdquoaforldquoappendrdquoandmodifiersonthese

WhatmodifierstothefilemodescanIuseThemostimportantonetoknowfornowisthe+modifiersoyoucandow+r+anda+Thiswillopenthefileinbothreadandwritemodeanddependingonthecharacterusepositionthefileindifferentways

Doesjustdoingopen(filename)openitinr(read)modeYesthatrsquosthedefaultfortheopen()function

Exercise17MoreFiles

NowletrsquosdoafewmorethingswithfilesWersquollwriteaPythonscripttocopyonefiletoanotherItrsquollbeveryshortbutwillgiveyouideasaboutotherthingsyoucandowithfilesClickheretoviewcodeimage

ex17py

1fromsysimportargv

2fromospathimportexists

3

4scriptfrom_fileto_file=argv

5

6print(fCopyingfromfrom_filetoto_file)

7

8wecoulddothesetwoononelinehow

9in_file=open(from_file)

10indata=in_fileread()

11

12print(fTheinputfileislen(indata)byteslong)

13

14print(fDoestheoutputfileexistexists(to_file))

15print(ReadyhitRETURNtocontinueCTRL-Ctoabort)

16input()

17

18out_file=open(to_filew)

19out_filewrite(indata)

20

21print(Alrightalldone)

22

23out_fileclose()

24in_fileclose()Youshouldimmediatelynoticethatweimport

anotherhandycommandnamedexistsThisreturnsTrueifafile

existsbasedonitsnameinastringasanargumentItreturns

FalseifnotWersquollbeusingthisfunctioninthesecondhalfofthis

booktodolotsofthingsbutrightnowyoushouldseehowyoucan

importit

Usingimportisawaytogettonsoffreecodeotherbetter(wellusually)programmershavewrittensoyoudonothavetowriteit

WhatYouShouldSee

JustlikeyourotherscriptsrunthisonewithtwoargumentsthefiletocopyfromandthefiletocopyittoIrsquomgoingtouseasimpletestfilenamedtesttxtClickheretoviewcodeimage

Exercise17Session

$firstmakeasamplefile

$echoThisisatestfilegttesttxt

$thenlookatit

$cattesttxt

Thisisatestfile

$nowrunourscriptonit

$python36ex17pytesttxtnew_filetxt

Copyingfromtesttxttonew_filetxt

Theinputfileis21byteslong

DoestheoutputfileexistFalse

ReadyhitRETURNtocontinueCTRL-Ctoabort

Alrightalldone

ItshouldworkwithanyfileTryabunchmoreandseewhathappensJustbecarefulyoudonotblastanimportantfile

WarningDidyouseethetrickIdidwithechotomakeafileandcattoshowthefileYoucanlearnhowtodothatintheAppendixldquoCommandLineCrashCourserdquo

StudyDrills1ThisscriptisreallyannoyingTherersquosnoneedtoaskyoubeforedoingthecopyanditprintstoomuchouttothescreenTrytomakethescriptmorefriendlytousebyremovingfeatures

2SeehowshortyoucanmakethescriptIcouldmakethisonelinelong3NoticeattheendoftheWhatYouShouldSeesectionIusedsomethingcalledcatItrsquosanoldcommandthatconcatenatesfilestogetherbutmostlyitrsquosjustaneasywaytoprintafiletothescreenTypemancattoreadaboutit

4Findoutwhyyouhadtowriteout_fileclose()inthecode

5GoreaduponPythonrsquosimportstatementandstartpython36totryitoutTryimportingsomethingsandseeifyoucangetitrightItrsquosalrightifyoudonot

CommonStudentQuestionsWhyisthewinquotesThatrsquosastringYoursquovebeenusingstringsforawhilenowMakesureyouknowwhatastringis

NowayyoucanmakethisonelineThatdependsonhowyoudefineonelineofcode

IsitnormaltofeellikethisexercisewasreallyhardYesitistotallynormalProgrammingmaynotldquoclickrdquoforyouuntilmaybeevenExercise36oritmightnotuntilyoufinishthebookandthenmakesomethingwithPythonEveryoneisdifferentsojustkeepgoingandkeepreviewingexercisesthatyouhadtroublewithuntilitclicksBepatient

Whatdoesthelen()functiondoItgetsthelengthofthestringthatyoupasstoitthenreturnsthatasanumberPlaywithit

WhenItrytomakethisscriptshorterIgetanerrorwhenIclosethefilesattheendYouprobablydidsomethinglikeindata=open(from_file)read()whichmeansyoudonrsquotneedtothendoin_fileclose()whenyoureachtheendofthescriptItshouldalreadybeclosedbyPythononcethatonelineruns

IgetaSyntaxEOLwhilescanningstringliteralerrorYouforgottoendastringproperlywithaquoteGolookatthatlineagain

Exercise18NamesVariablesCodeFunctions

BigtitlerightIamabouttointroduceyoutothefunctionDumdumdahEveryprogrammerwillgoonandonaboutfunctionsandallthedifferentideasabouthowtheyworkandwhattheydobutIwillgiveyouthesimplestexplanationyoucanuserightnowFunctionsdothreethings1Theynamepiecesofcodethewayvariablesnamestringsandnumbers

2Theytakeargumentsthewayyourscriptstakeargv3Using1and2theyletyoumakeyourownldquomini-scriptsrdquoorldquotinycommandsrdquo

YoucancreateafunctionbyusingtheworddefinPythonIrsquomgoingtohaveyoumakefourdifferentfunctionsthatworklikeyourscriptsandthenIrsquollshowyouhoweachoneisrelatedClickheretoviewcodeimage

ex18py

1thisoneislikeyourscriptswithargv

2defprint_two(args)

3arg1arg2=args

4print(farg1arg1arg2arg2)

5

6okthatargsisactuallypointlesswecanjustdothis

7defprint_two_again(arg1arg2)

8print(farg1arg1arg2arg2)

9

10thisjusttakesoneargument

11defprint_one(arg1)

12print(farg1arg1)

13

14thisonetakesnoarguments

15defprint_none()

16print(Igotnothin)

17

18

19print_two(ZedShaw)

20print_two_again(ZedShaw)

21print_one(First)

22print_none()Letrsquosbreakdownthefirstfunctionprint_two

whichisthemostsimilartowhatyoualreadyknowfrommaking

scripts1WetellPythonwewanttomakeafunctionusingdeffor

ldquodefinerdquo

2OnthesamelineasdefwegivethefunctionanameInthiscasewejustcalleditldquoprint_twordquobutitcouldalsobeldquopeanutsrdquoItdoesnrsquotmatterexceptthatyourfunctionshouldhaveashortnamethatsayswhatitdoes

3Wetellitwewantargs(asteriskargs)whichisalotlikeyourargvparameterbutforfunctionsThishastogoinsideparenthesestowork

4Weendthislinewitha(colon)andstartindenting5Afterthecolonallthelinesthatareindentedfourspaceswillbecomeattachedtoprint_twoOurfirstindentedlineisonethatunpackstheargumentsthesameaswithyourscripts

6Todemonstratehowitworksweprinttheseargumentsoutjustlikewewouldinascript

Theproblemwithprint_twoisthatitrsquosnottheeasiestwaytomakeafunctionInPythonwecanskipthewholeunpackingargumentsandjustusethenameswewantrightinsideparenthesesThatrsquoswhatprint_two_againdoesAfterthatyouhaveanexampleofhowyoumakeafunctionthattakesoneargumentinprint_oneFinallyyouhaveafunctionthathasnoargumentsinprint_none

WarningThisisveryimportantDonotgetdiscouragedrightnowifthisdoesnrsquotquitemakesenseWersquoregoingtodoafewexerciseslinkingfunctionstoyourscriptsandshowyouhowtomakemoreFornowjustkeepthinkingldquomini-scriptrdquowhenIsayldquofunctionrdquoandkeepplayingwiththem

WhatYouShouldSeeIfyourunex18pyyoushouldsee

Exercise18Session

$python36ex18py

arg1Zedarg2Shaw

arg1Zedarg2Shaw

arg1First

Igotnothin

RightawayyoucanseehowafunctionworksNoticethatyouusedyourfunctionsthewayyouusethingslikeexistsopenandothercommandsInfactIrsquovebeentrickingyoubecauseinPythonthosecommandsarejustfunctionsThismeansyoucanmakeyourowncommandsandusetheminyourscriptstoo

StudyDrillsCreateafunctionchecklistforlaterexercisesWritethesechecksonanindexcardandkeepitbyyouwhileyoucompletetherestoftheseexercisesoruntilyoufeelyoudonotneedtheindexcardanymore

1Didyoustartyourfunctiondefinitionwithdef2Doesyourfunctionnamehaveonlycharactersand_(underscore)characters

3Didyouputanopenparenthesisrightafterthefunctionname4Didyouputyourargumentsaftertheparenthesisseparatedbycommas5Didyoumakeeachargumentunique(meaningnoduplicatednames)6Didyouputacloseparenthesisandacolonafterthearguments7DidyouindentalllinesofcodeyouwantinthefunctionfourspacesNomorenoless

8Didyouldquoendrdquoyourfunctionbygoingbacktowritingwithnoindent(dedentingwecallit)

Whenyourun(ldquouserdquoorldquocallrdquo)afunctioncheckthesethings1Didyoucalluserunthisfunctionbytypingitsname

2Didyouputthe(characterafterthenametorunit3Didyouputthevaluesyouwantintotheparenthesesseparatedbycommas

4Didyouendthefunctioncallwitha)characterUsethesetwochecklistsontheremaininglessonsuntilyoudonotneedthemanymoreFinallyrepeatthisafewtimestoyourselfToldquorunrdquoldquocallrdquoorldquouserdquoafunctioneachmeansthesamething

CommonStudentQuestions

CommonStudentQuestionsWhatrsquosallowedforafunctionnameThesameasvariablenamesAnythingthatdoesnrsquotstartwithanumberandislettersnumbersandunderscoreswillwork

WhatdoestheinargsdoThattellsPythontotakealltheargumentstothefunctionandthenputtheminargsasalistItrsquoslikeargvthatyoursquovebeenusingbutforfunctionsItrsquosnotnormallyusedtoooftenunlessspecificallyneeded

ThisfeelsreallyboringandmonotonousThatrsquosgoodItmeansyoursquorestartingtogetbetterattypinginthecodeandunderstandingwhatitdoesTomakeitlessboringtakeeverythingItellyoutotypeinandthenbreakitonpurpose

Exercise19FunctionsandVariables

Functionsmayhavebeenamind-blowingamountofinformationbutdonotworryJustkeepdoingtheseexercisesandgoingthroughyourchecklistfromthelastexerciseandyouwilleventuallygetitThereisonetinypointthatyoumightnothaverealizedwhichwersquollreinforcerightnowThevariablesinyourfunctionarenotconnectedtothevariablesinyourscriptHerersquosanexercisetogetyouthinkingaboutthisClickheretoviewcodeimage

ex19py

1defcheese_and_crackers(cheese_countboxes_of_crackers)

2print(fYouhavecheese_countcheeses)

3print(fYouhaveboxes_of_crackersboxesofcrackers)

4print(Manthatsenoughforaparty)

5print(Getablanketn)

6

7

8print(Wecanjustgivethefunctionnumbersdirectly)

9cheese_and_crackers(2030)

10

11

12print(ORwecanusevariablesfromourscript)

13amount_of_cheese=10

14amount_of_crackers=50

15

16cheese_and_crackers(amount_of_cheeseamount_of_crackers)

17

18

19print(Wecanevendomathinsidetoo)

20cheese_and_crackers(10+205+6)

21

22

23print(Andwecancombinethetwovariablesandmath)

24cheese_and_crackers(amount_of_cheese+100amount_of_crackers

+1000)Thisshowsallthedifferentwayswersquoreabletogiveour

functioncheese_and_crackersthevaluesitneedstoprintthemWe

cangiveitstraightnumbersWecangiveitvariablesWecangive

itmathWecanevencombinemathandvariables

Inawaytheargumentstoafunctionarekindoflikeour=characterwhenwemakeavariableInfactifyoucanuse=tonamesomethingyoucanusually

passittoafunctionasanargument

WhatYouShouldSeeYoushouldstudytheoutputofthisscriptandcompareitwithwhatyouthinkyoushouldgetforeachoftheexamplesinthescriptClickheretoviewcodeimage

Exercise19Session

$python36ex19py

Wecanjustgivethefunctionnumbersdirectly

Youhave20cheeses

Youhave30boxesofcrackers

Manthatsenoughforaparty

Getablanket

ORwecanusevariablesfromourscript

Youhave10cheeses

Youhave50boxesofcrackers

Manthatsenoughforaparty

Getablanket

Wecanevendomathinsidetoo

Youhave30cheeses

Youhave11boxesofcrackers

Manthatsenoughforaparty

Getablanket

Andwecancombinethetwovariablesandmath

Youhave110cheeses

Youhave1050boxesofcrackers

Manthatsenoughforaparty

Getablanket

StudyDrills1GobackthroughthescriptandtypeacommentaboveeachlineexplaininginEnglishwhatitdoes

2Startatthebottomandreadeachlinebackwardsayingalltheimportantcharacters

3Writeatleastonemorefunctionofyourowndesignandrunit10differentways

CommonStudentQuestions

Howcantherepossiblybe10differentwaystorunafunctionBelieveitornottherersquosatheoreticallyinfinitenumberofwaystocallanyfunctionSeehowcreativeyoucangetwithfunctionsvariablesandinputfromauser

IsthereawaytoanalyzewhatthisfunctionisdoingsoIcanunderstanditbetterTherearemanydifferentwaysbuttryputtinganEnglishcommentaboveeachlinedescribingwhatthelinedoesAnothertrickistoreadthecodeoutloudYetanotheristoprintthecodeoutanddrawonthepaperwithpicturesandcommentsshowingwhatrsquosgoingon

WhatifIwanttoasktheuserforthenumbersofcheeseandcrackersYouneedtouseint()toconvertwhatyougetfrominput()

Doesmakingthevariableamount_of_cheesechangethevariablecheese_countinthefunctionNothosevariablesareseparateandliveoutsidethefunctionTheyarethenpassedtothefunctionandtemporaryversionsaremadejustforthefunctionrsquosrunWhenthefunctionexitsthesetemporaryvariablesgoawayandeverythingkeepsworkingKeepgoinginthebookandthisshouldbecomeclearer

Isitbadtohaveglobalvariables(likeamount_of_cheese)withthesamenameasfunctionvariablesYessincethenyoursquorenotquitesurewhichoneyoursquoretalkingaboutButsometimesnecessitymeansyouhavetousethesamenameoryoumightdoitonaccidentJustavoiditwheneveryoucan

IstherealimittothenumberofargumentsafunctioncanhaveItdependsontheversionofPythonandthecomputeryoursquoreonbutitisfairlylargeThepracticallimitthoughisaboutfiveargumentsbeforethefunctionbecomesannoyingtouse

CanyoucallafunctionwithinafunctionYesyoursquollmakeagamethatdoesthislaterinthebook

Exercise20FunctionsandFiles

RememberyourchecklistforfunctionsthendothisexercisepayingcloseattentiontohowfunctionsandfilescanworktogethertomakeusefulstuffClickheretoviewcodeimage

ex20py

1fromsysimportargv

2

3scriptinput_file=argv

4

5defprint_all(f)

6print(fread())

7

8defrewind(f)

9fseek(0)

10

11defprint_a_line(line_countf)

12print(line_countfreadline())

13

14current_file=open(input_file)

15

16print(Firstletsprintthewholefilen)

17

18print_all(current_file)

19

20print(Nowletsrewindkindoflikeatape)

21

22rewind(current_file)

23

24print(Letsprintthreelines)

25

26current_line=1

27print_a_line(current_linecurrent_file)

28

29current_line=current_line+1

30print_a_line(current_linecurrent_file)

31

32current_line=current_line+1

33print_a_line(current_linecurrent_file)Paycloseattentionto

howwepassinthecurrentlinenumbereachtimewerunprint_a_line

WhatYouShouldSee

Clickheretoviewcodeimage

Exercise20Session

$python36ex20pytesttxt

Firstletsprintthewholefile

Thisisline1

Thisisline2

Thisisline3

Nowletsrewindkindoflikeatape

Letsprintthreelines

1Thisisline1

2Thisisline2

3Thisisline3

StudyDrills1WriteanEnglishcommentforeachlinetounderstandwhatthatlinedoes2Eachtimeprint_a_lineisrunyouarepassinginavariablecurrent_lineWriteoutwhatcurrent_lineisequaltooneachfunctioncallandtracehowitbecomesline_countinprint_a_line

3Findeachplaceafunctionisusedandcheckitsdeftomakesurethatyouaregivingittherightarguments

4ResearchonlinewhattheseekfunctionforfiledoesTrypydocfileandseeifyoucanfigureitoutfromthereThentrypydocfileseektoseewhatseekdoes

5Researchtheshorthandnotation+=andrewritethescripttouse+=instead

CommonStudentQuestionsWhatisfintheprint_allandotherfunctionsThefisavariablejustlikeyouhadinotherfunctionsinExercise18exceptthistimeitrsquosafileAfileinPythoniskindoflikeanoldtapedriveonamainframeormaybeaDVDplayerIthasaldquoreadheadrdquoandyoucanldquoseekrdquothisreadheadaroundthefiletopositionsthenworkwithitthereEachtimeyoudofseek(0)yoursquoremovingtothe

startofthefileEachtimeyoudofreadline()yoursquorereadingalinefromthefileandmovingthereadheadtorightafterthenthatendsthatlineThiswillbeexplainedmoreasyougoon

Whydoesseek(0)notsetthecurrent_lineto0Firsttheseek()functionisdealinginbytesnotlinesThecodeseek(0)movesthefiletothe0byte(firstbyte)inthefileSecondcurrent_lineisjustavariableandhasnorealconnectiontothefileatallWearemanuallyincrementingit

Whatis+=YouknowhowinEnglishIcanrewriteldquoitisrdquoasldquoitrsquosrdquoOrIcanrewriteldquoyouarerdquoasldquoyoursquorerdquoInEnglishthisiscalledacontractionandthisiskindoflikeacontractionforthetwooperations=and+Thatmeansx=x+yisthesameasx+=y

Howdoesreadline()knowwhereeachlineisInsidereadline()iscodethatscanseachbyteofthefileuntilitfindsancharacterthenstopsreadingthefiletoreturnwhatitfoundsofarThefilefisresponsibleformaintainingthecurrentpositioninthefileaftereachreadline()callsothatitwillkeepreadingeachline

WhyarethereemptylinesbetweenthelinesinthefileThereadline()functionreturnsthenthatrsquosinthefileattheendofthatlineAddaend=attheendofyourprintfunctioncallstoavoidaddingdoublentoeveryline

Exercise21FunctionsCanReturnSomething

Youhavebeenusingthe=charactertonamevariablesandsetthemtonumbersorstringsWersquorenowgoingtoblowyourmindagainbyshowingyouhowtouse=andanewPythonwordreturntosetvariablestobeavaluefromafunctionTherewillbeonethingtopaycloseattentiontobutfirsttypethisinClickheretoviewcodeimage

ex21py

1defadd(ab)

2print(fADDINGa+b)

3returna+b

4

5defsubtract(ab)

6print(fSUBTRACTINGa-b)

7returna-b

8

9defmultiply(ab)

10print(fMULTIPLYINGab)

11returnab

12

13defdivide(ab)

14print(fDIVIDINGab)

15returnab

16

17

18print(Letsdosomemathwithjustfunctions)

19

20age=add(305)

21height=subtract(784)

22weight=multiply(902)

23iq=divide(1002)

24

25print(fAgeageHeightheightWeightweightIQ

iq)

26

27

28Apuzzlefortheextracredittypeitinanyway

29print(Hereisapuzzle)

30

31what=add(agesubtract(heightmultiply(weightdivide(iq

2))))

32

33print(ThatbecomeswhatCanyoudoitbyhand)Weare

nowdoingourownmathfunctionsforaddsubtractmultiplyand

divideTheimportantthingtonoticeisthelastlinewherewesay

returna+b(inadd)Whatthisdoesisthefollowing1Our

functioniscalledwithtwoargumentsaandb

2WeprintoutwhatourfunctionisdoinginthiscaseldquoADDINGrdquo3WetellPythontodosomethingkindofbackwardwereturntheadditionofa+bYoumightsaythisasldquoIaddaandbthenreturnthemrdquo

4PythonaddsthetwonumbersThenwhenthefunctionendsanylinethatrunsitwillbeabletoassignthisa+bresulttoavariable

AswithmanyotherthingsinthisbookyoushouldtakethisrealslowbreakitdownandtrytotracewhatrsquosgoingonTohelpthereisextracredittosolveapuzzleandlearnsomethingcool

WhatYouShouldSeeClickheretoviewcodeimage

Exercise21Session

$python36ex21py

Letsdosomemathwithjustfunctions

ADDING30+5

SUBTRACTING78-4

MULTIPLYING902

DIVIDING1002

Age35Height74Weight180IQ500

Hereisapuzzle

DIVIDING5002

MULTIPLYING180250

SUBTRACTING74-45000

ADDING35+-44260

Thatbecomes-43910Canyoudoitbyhand

StudyDrills1IfyouarenrsquotreallysurewhatreturndoestrywritingafewofyourownfunctionsandhavethemreturnsomevaluesYoucanreturnanythingthatyoucanputtotherightofan=

2AttheendofthescriptisapuzzleIrsquomtakingthereturnvalueofonefunctionandusingitastheargumentofanotherfunctionIrsquomdoingthisinachainsothatIrsquomkindofcreatingaformulausingthefunctionsItlooks

reallyweirdbutifyourunthescriptyoucanseetheresultsWhatyoushoulddoistrytofigureoutthenormalformulathatwouldrecreatethissamesetofoperations

3OnceyouhavetheformulaworkedoutforthepuzzlegetinthereandseewhathappenswhenyoumodifythepartsofthefunctionsTrytochangeitonpurposetomakeanothervalue

4DotheinverseWriteasimpleformulaandusethefunctionsinthesamewaytocalculateit

ThisexercisemightreallywhackyourbrainoutbuttakeitslowandeasyandtreatitlikealittlegameFiguringoutpuzzleslikethisiswhatmakesprogrammingfunsoIrsquollbegivingyoumorelittleproblemslikethisaswego

CommonStudentQuestionsWhydoesPythonprinttheformulaorthefunctionsldquobackwardrdquoItrsquosnotreallybackwarditrsquosldquoinsideoutrdquoWhenyoustartbreakingdownthefunctionintoseparateformulasandfunctioncallsyoursquollseehowitworksTrytounderstandwhatImeanbyldquoinsideoutrdquoratherthanldquobackwardrdquo

HowcanIuseinput()toentermyownvaluesRememberint(input())Theproblemwiththatisthenyoucanrsquotenterfloatingpointsoalsotryusingfloat(input())instead

WhatdoyoumeanbyldquowriteoutaformulardquoTry24+34100-1023asastartConvertthattousethefunctionsNowcomeupwithyourownsimilarmathequationandusevariablessoitrsquosmorelikeaformula

Exercise22WhatDoYouKnowSoFar

TherewonrsquotbeanycodeinthisexerciseorthenextonesotherersquosnoWhatYouShouldSeeorStudyDrillssectionsInfactthisexerciseislikeonegiantStudyDrillsIrsquomgoingtohaveyoudoareviewofwhatyouhavelearnedsofarFirstgobackthrougheveryexerciseyouhavedonesofarandwritedowneverywordandsymbol(anothernameforldquocharacterrdquo)thatyouhaveusedMakesureyourlistofsymbolsiscompleteNexttoeachwordorsymbolwriteitsnameandwhatitdoesIfyoucanrsquotfindanameforasymbolinthisbookthenlookforitonlineIfyoudonotknowwhatawordorsymboldoesthenreadaboutitagainandtryusingitinsomecodeYoumayrunintoafewthingsyoucanrsquotfindoutorknowsojustkeepthoseonthelistandbereadytolookthemupwhenyoufindthemOnceyouhaveyourlistspendafewdaysrewritingthelistanddouble-checkingthatitrsquoscorrectThismaygetboringbutpushthroughandreallynailitdownOnceyouhavememorizedthelistandwhattheydothenstepitupbywritingouttablesofsymbolstheirnamesandwhattheydofrommemoryIfyouhitsomeyoucanrsquotrecallfrommemorygobackandmemorizethemagain

WarningThemostimportantthingwhendoingthisexerciseisldquoThereisnofailureonlytryingrdquo

WhatYouAreLearningItrsquosimportantwhenyouaredoingaboringmindlessmemorizationexerciselikethistoknowwhyIthelpsyoufocusonagoalandknowthepurposeofallyoureffortsInthisexerciseyouarelearningthenamesofsymbolssothatyoucanreadsourcecodemoreeasilyItrsquossimilartolearningthealphabetandbasicwordsofEnglishexceptthisPythonalphabethasextrasymbolsyoumightnotknowJusttakeitslowanddonothurtyourbrainItrsquosbesttotake15minutesatatimewithyourlistandthentakeabreakGivingyourbrainarestwillhelpyoulearnfasterwithlessfrustration

Exercise23StringsBytesandCharacterEncodings

TodothisexerciseyoursquollneedtodownloadatextfilethatIrsquovewrittennamedlanguagestxt(httpslearnpythonthehardwayorgpython3languagestxt)Thisfilewascreatedwithalistofhumanlanguagestodemonstrateafewinterestingconcepts

1HowmoderncomputersstorehumanlanguagesfordisplayandprocessingandhowPython3callsthisstrings

2HowyoumustldquoencoderdquoandldquodecoderdquoPythonrsquosstringsintoatypecalledbytes

3Howtohandleerrorsinyourstringandbytehandling4Howtoreadcodeandfindoutwhatitmeansevenifyoursquoveneverseenitbefore

InadditiontothatyoursquollalsogetabriefglimpseofthePython3if-statementandlistsforprocessingalistofthingsYoudonrsquothavetomasterthiscodeorunderstandtheseconceptsrightawayYoursquollgetplentyofpracticeinlaterexercisesFornowyourjobistogetatasteofthefutureandlearnthefourtopicsintheprecedinglist

WarningThisexerciseishardTherersquosalotofinformationinitthatyouneedtounderstandanditrsquosinformationthatgoesdeepintocomputersThisexerciseiscomplexbecausePythonrsquosstringsarecomplexanddifficulttouseIrecommendyoutakethisexercisepainfullyslowWritedowneverywordyoudonrsquotunderstandandlookituporresearchitTakeaparagraphatatimeifyoumustYoucancontinuewithotherexerciseswhileyoustudythisonesodonrsquotgetstuckhereJustchipawayatitforaslongasittakes

InitialResearchIrsquomgoingtoteachyouhowtoresearchapieceofcodetoexposeitssecretsYoursquollneedthelanguagestxtfileforthiscodetoworksomakesureyoudownloaditfirstThelanguagestxtfilesimplycontainsalistofhumanlanguagenamesthatareencodedinUTF-8Clickheretoviewcodeimage

ex23py

1importsys

2scriptencodingerror=sysargv

3

4

5defmain(language_fileencodingerrors)

6line=language_filereadline()

7

8ifline

9print_line(lineencodingerrors)

10returnmain(language_fileencodingerrors)

11

12

13defprint_line(lineencodingerrors)

14next_lang=linestrip()

15raw_bytes=next_langencode(encodingerrors=errors)

16cooked_string=raw_bytesdecode(encodingerrors=errors)

17

18print(raw_byteslt===gtcooked_string)

19

20

21languages=open(languagestxtencoding=utf-8)

22

23main(languagesencodingerror)

SimplywritedownalistofeachthingyoursquoveneverseenbeforeTheremaybequiteafewthingsthatarenewsoscanthefileafewtimesOnceyouhavethatyoursquollwanttorunthisPythonscripttoplaywithitHerearesomeexamplecommandsIusedtotestit

WarningYoursquollnoticeIrsquomusingimagesheretoshowyouwhatyoushouldseeAfterextensivetestingitturnsoutthatsomanypeoplehave

seeAfterextensivetestingitturnsoutthatsomanypeoplehavetheircomputersconfiguredtonotdisplayUTF-8thatIhadtouseimagessoyoursquollknowwhattoexpectEvenmyowntypesettingsystem(LaTeX)couldnrsquothandletheseencodingsforcingmetouseimagesinsteadIfyoudonrsquotseethisthenyourTerminalismostlikelynotabletodisplayUTF-8andyoushouldtrytofixthat

Theseexamplesusetheutf-8utf-16andbig5encodingstodemonstratetheconversionandthetypesoferrorsyoucangetEachofthesenamesarecalledaldquocodecrdquoinPython3butyouusetheparameterldquoencodingrdquoAttheendofthisexercisetherersquosalistoftheavailableencodingsifyouwanttotrymoreIrsquollcoverwhatallofthisoutputmeansshortlyYoursquoreonlytryingtogetanideaofhowthisworkssowecantalkaboutitAfteryoursquoverunitafewtimesgothroughyourlistofsymbolsandmakeaguessastowhattheydoWhenyoursquovewrittendownyourguessestrylookingthesymbolsuponlinetoseeifyoucanconfirmyourhypothesesDonrsquotworryifyouhavenoideahowtosearchforthemJustgiveitatry

SwitchesConventionsandEncodingsBeforeIcangetintowhatthiscodemeansyouneedtolearnsomebasicsabouthowdataisstoredinacomputerModerncomputersareincrediblycomplexbutattheircorestheyarelikeahugearrayoflightswitchesComputersuseelectricitytoflipswitchesonoroffTheseswitchescanrepresent1foronor0foroffIntheolddaystherewereallkindsofweirdcomputersthatdidmorethanjust1or0butthesedaysitrsquosjust1sand0sOnerepresentsenergyelectricityonpowersubstanceZerorepresentsoffdonegonepowerdownthelackofenergyWecallthese1sand0sldquobitsrdquoNowacomputerthatonlyletsyouworkwith1and0wouldbebothhorriblyinefficientandincrediblyannoyingComputerstakethese1sand0sandusethemtoencodelargernumbersAtthesmallendacomputerwilluse8ofthese1sand0stoencode256numbers(0-255)WhatdoesldquoencoderdquomeanthoughItrsquosnothingmorethananagreed-uponstandardforhowasequenceofbitsshouldrepresentanumberItrsquosaconventionhumanspickedorstumbledonthatsaysthat00000000wouldbe011111111wouldbe255and00001111wouldbe15TherewereevenhugewarsintheearlyhistoryofcomputersonnothingmorethantheorderofthesebitsbecausetheyweresimplyconventionsweallhadtoagreeonTodaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryone

Todaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryonehadtheirownconventionforabytesoyoursquollstillrunintopeoplewhothinkthatthistermshouldbeflexibleandhandlesequencesof9bits7bitsor6bitsbutnowwejustsayitrsquos8bitsThatrsquosourconventionandthatconventiondefinesourencodingforabyteTherearefutherconventionsforencodinglargenumbersusing163264andevenmorebitsifyougetintoreallybigmathTherersquosentirestandardsgroupswhodonothingbutargueabouttheseconventionsthenimplementthemasencodingsthateventuallyturnswitchesonandoffOnceyouhavebytesyoucanstarttostoreanddisplaytextbydecidingonanotherconventionforhowanumbermapstoaletterIntheearlydaysofcomputingthereweremanyconventionsthatmapped8or7bits(orlessormore)ontolistsofcharacterskeptinsideacomputerThemostpopularconventionendedupbeingAmericanStandardCodeforInformationInterchangeorASCIIThisstandardmapsanumbertoaletterThenumber90isZwhichinbitsis1011010whichgetsmappedtotheASCIItableinsidethecomputerYoucantrythisoutinPythonrightnow

gtgtgt0b1011010

90

gtgtgtord(Z)

90

gtgtgtchr(90)

Z

gtgtgt

FirstIwritethenumber90inbinarythenIgetthenumberbasedontheletterZthenIconvertthenumbertotheletterZDonrsquotworryaboutneedingtorememberthisthoughIthinkIrsquovehadtodoittwicetheentiretimeIrsquoveusedPythonOncewehavetheASCIIconventionforencodingacharacterusing8bits(abyte)wecanthenldquostringrdquothemtogethertomakeawordIfIwanttowritemynameldquoZedAShawrdquoIjustuseasequenceofbytes[90101100326546328310497119]MostoftheearlytextincomputerswasnothingmorethansequencesofbytesstoredinmemorythatacomputerusedtodisplaytexttoapersonAgainthisisjustasequenceofconventionsthatturnedswitchesonandoffTheproblemwithASCIIisthatitonlyencodesEnglishandmaybeafewothersimilarlanguagesRememberthatabytecanhold256numbers(0-255or

00000000-11111111)Turnsouttherersquosalotmorecharactersthan256usedthroughouttheworldrsquoslanguagesDifferentcountriescreatedtheirownencodingconventionsfortheirlanguagesandthatmostlyworkedbutmanyencodingscouldonlyhandleonelanguageThatmeantifyouwanttoputthetitleofanAmericanEnglishbookinthemiddleofaThaisentenceyouwerekindofintroubleYoursquodneedoneencodingforThaiandoneforEnglishTosolvethisproblemagroupofpeoplecreatedUnicodeItsoundslikeldquoencoderdquoanditismeanttobealdquouniversalencodingrdquoofallhumanlanguagesThesolutionUnicodeprovidesisliketheASCIItablebutitrsquoshugebycomparisonYoucanuse32bitstoencodeaUnicodecharacterandthatismorecharactersthanwecouldpossiblyfindA32-bitnumbermeanswecanstore4294967295characters(2^32)whichisenoughspaceforeverypossiblehumanlanguageandprobablyalotofalienonestooRightnowweusetheextraspaceforimportantthingslikepoopandsmileemojisWenowhaveaconventionforencodinganycharacterswewantbut32bitsis4bytes(328==4)whichmeansthereissomuchwastedspaceinmosttextwewanttoencodeWecanalsouse16bits(2bytes)butstilltherersquosgoingtobewastedspaceinmosttextThesolutionistouseacleverconventiontoencodemostcommoncharactersusing8bitsandthenldquoescaperdquointolargernumberswhenweneedtoencodemorecharactersThatmeanswehaveonemoreconventionthatisnothingmorethanacompressionencodingmakingitpossibleformostcommoncharacterstouse8bitsandthenescapeoutinto16or32bitsasneededTheconventionforencodingtextinPythoniscalledldquoUTF-8rdquowhichmeansldquoUnicodeTransformationFormat8BitsrdquoItisaconventionforencodingUnicodecharactersintosequencesofbyteswhicharesequencesofbitswhichturnsequencesofswitchesonandoffYoucanalsouseotherconventions(encodings)butUTF-8isthecurrentstandard

DisectingtheOutputWecannowlookattheoutputofthecommandsshownpreviouslyLetrsquostakejustthatfirstcommandandthefirstfewlinesofoutput

Theex23pyscriptistakingbyteswritteninsidetheb(bytestring)andconvertingthemtotheUTF-8(orother)encodingyouspecifiedOntheleftisthenumbersforeachbyteoftheUTF-8(showninhexadecimal)andtherighthasthecharacteroutputasactualUTF-8Thewaytothinkofthisistheleftsideoflt===gtisthePythonnumericalbytesortheldquorawrdquobytesPythonusestostorethestringYouspecifythiswithbtotellPythonthisisbytesTheserawbytesarethendisplayedldquocookedrdquoontherightsoyoucanseetherealcharactersinyourTerminal

DisectingtheCodeWehaveanunderstandingofstringsandbytesequencesInPythonastringisaUTF-8encodedsequenceofcharactersfordisplayingorworkingwithtextThebytesarethentheldquorawrdquosequenceofbytesthatPythonusestostorethisUTF-8stringandstartwithabtotellPythonyouareworkingwithrawbytesThisisallbasedonconventionsforhowPythonwantstoworkwithtextHerersquosaPythonsessionshowingmeencodingstringsanddecodingbytes

Allyouneedtorememberisifyouhaverawbytesthenyoumustusedecode()togetthestringRawbyteshavenoconventiontothemTheyarejustsequencesofbyteswithnomeaningotherthannumberssoyoumusttellPythontoldquodecodethisintoaUTFstringrdquoIfyouhaveastringandwanttosenditstoreitshareitordosomeotheroperationthenusuallyitrsquollworkbutsometimesPythonwillthrowupanerrorsayingitdoesnrsquotknowhowtoldquoencoderdquoitAgainPythonknowsitsinternalconventionbutithasnoideawhatconventionyouneedInthatcaseyoumustuseencode()togetthebytesyouneedThewaytorememberthis(eventhoughIlookitupalmosteverytime)istorememberthemnemonicDBESwhichstandsforDecodeBytesEncodeStringsIsayldquodeebessrdquoinmyheadwhenIhavetoconvertbytesandstringsWhenyouhavebytesandneedastringdecodebytesWhenyouhaveastringandneedbytesencodestringsWiththatinmindletrsquosbreakdownthecodeinex23pyline-by-line1ndash2Istartwiththeusualcommandlineargumenthandlingthatyoualready

know5IstartthemainmeatofthiscodeinafunctionconvenientlycalledmainThiswillbecalledattheendofthisscripttogetthingsgoing

6ThefirstthingthisfunctiondoesisreadonelinefromthelanguagesfileitisgivenYouhavedonethisbeforesonothingnewhereJustreadlineasbeforewhendealingwithtextfiles

8IusesomethingnewYouwilllearnaboutthisinthesecondhalfofthebooksoconsiderthisateaserofinterestingthingstocomeThisisanif-statementanditletsyoumakedecisionsinyourPythoncodeYoucantestthetruthofavariableandbasedonthattruthrunapieceofcodeornotrunitInthiscaseIrsquomtestingwhetherlinehassomethinginitThereadlinefunctionwillreturnanemptystringwhenitreachestheendofthefileandiflinesimplytestsforthisemptystringAslongasreadlinegivesussomethingthiswillbetrueandthecodeunder(indentedinlines9ndash10)willrunWhenthisisfalsePythonwillskiplines9ndash10

9IcallaseparatefunctiontodotheactualprintingofthislineThissimplifiesmycodeandmakesiteasierformetounderstanditIfIwanttolearnwhatthisfunctiondoesIcanjumptoitandstudyOnceIknowwhatprint_linedoesIcanattachmymemorytothenameprint_line

andforgetaboutthedetails10IhavewrittenatinyyetpowerfulpieceofmagichereIamcallingmainagaininsidemainActuallyitrsquosnotmagicsincenothingreallyismagicalinprogrammingAlltheinformationyouneedisthereThislookslikeIamcallingthefunctioninsideitselfwhichseemslikeitshouldbeillegaltodoAskyourselfwhyshouldthatbeillegalTherersquosnotechnicalreasonwhyIcanrsquotcallanyfunctionIwantrightthereeventhismainfunctionIfafunctionissimplyajumptothetopwhereIrsquovenameditmainthencallingthisfunctionattheendofitselfwouldjumpbacktothetopandrunitagainThatwouldmakeitloopNowlookbackatline8andyoursquollseetheif-statementkeepsthisfunctionfromloopingforeverCarefullystudythisbecauseitisasignificantconceptbutdonrsquotworryifyoucanrsquotgraspitrightaway

13Istartthedefinitionfortheprint_linefunctionwhichdoestheactualencodingofeachlinefromthelanguagestxtfile

14Thisisasimplestrippingofthetrailingnonthelinestring15IfinallytakethelanguageIrsquovereceivedfromthelanguagestxtfileandencodeitintotherawbytesRemembertheDBESmnemonicDecodebytesencodestringsThenext_langvariableisastringsotogettherawbytesImustcallencode()onittoencodestringsIpasstoencode()theencodingIwantandhowtohandleerrors

16Idotheextrastepofshowingtheinverseofline15bycreatingacooked_stringvariablefromtheraw_bytesRememberDBESsaysIdecodebytesandraw_bytesisbytessoIcalldecode()onittogetaPythonstringThisstringshouldbethesameasthenext_langvariable

18Isimplyprintthembothouttoshowyouwhattheylooklike21IrsquomdonedefiningfunctionssonowIwanttoopenthelanguagestxtfile

23Theendofthescriptsimplyrunsthemainfunctionwithallthecorrectparameterstogeteverythinggoingandkick-starttheloopRememberthatthisthenjumpstowherethemainfunctionisdefinedonline5andonline10mainiscalledagaincausingthistokeeploopingTheiflineonline8willpreventourloopfromgoingforever

EncodingsDeepDive

WecannowuseourlittlescripttoexploreotherencodingsThefollowingshowsmeplayingwithdifferentencodingsandseeinghowtobreakthemFirstIrsquomdoingasimpleUTF-16encodingsoyoucanseehowitchangescomparedtoUTF-8YoucanalsouseUTF-32toseehowthatrsquosevenbiggerandgetanideaofthespacesavedwithUTF-8AfterthatItryBig5andyoursquollseethatPythondoesnotlikethatatallItthrowsupanerrorthatBig5canrsquotencodesomeofthecharactersatposition0(whichissuperhelpful)OnesolutionistotellPythontoldquoreplacerdquoanybadcharactersfortheBig5encodingThatrsquosthenextexampleandyoursquollseeitputsacharacterwhereveritfindsacharacterthatdoesnrsquotmatchtheBig5encodingsystem

BreakingItRoughideasincludethefollowing

1Findstringsoftextencodedinotherencodingsandplacethemintheex23pyfiletoseehowitbreaks

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist3ExtrachallengingRewritethisusingthebbytesinsteadoftheUTF-8stringseffectivelyreversingthescript

4IfyoucandothatthenyoucanalsobreakthesebytesbyremovingsometoseewhathappensHowmuchdoyouneedtoremovetocausePythontobreakHowmuchcanyouremovetodamagethestringoutputbutpassPythonrsquosdecodingsystem

5Usewhatyoulearnedfromitem4toseeifyoucanmanglethefilesWhaterrorsdoyougetHowmuchdamagecanyoucauseandgetthefilepastPythonrsquosdecodingsystem

Exercise24MorePractice

YouaregettingtotheendofthissectionYoushouldhaveenoughPythonldquounderyourfingersrdquotomoveontolearningabouthowprogrammingreallyworksbutyoushoulddosomemorepracticeThisexerciseislongerandallaboutbuildingupstaminaThenextexercisewillbesimilarDothemgetthemexactlyrightanddoyourchecksClickheretoviewcodeimage

ex24py

1print(Letspracticeeverything)

2print(Youdneedtoknowboutescapeswiththatdo)

3print(nnewlinesandttabs)

4

5poem=

6tThelovelyworld

7withlogicsofirmlyplanted

8cannotdiscernntheneedsoflove

9norcomprehendpassionfromintuition

10andrequiresanexplanation

11nttwherethereisnone

12

13

14print(--------------)

15print(poem)

16print(--------------)

17

18

19five=10-2+3-6

20print(fThisshouldbefivefive)

21

22defsecret_formula(started)

23jelly_beans=started500

24jars=jelly_beans1000

25crates=jars100

26returnjelly_beansjarscrates

27

28

29start_point=10000

30beansjarscrates=secret_formula(start_point)

31

32rememberthatthisisanotherwaytoformatastring

33print(Withastartingpointofformat(start_point))

34itsjustlikewithanfstring

35print(fWedhavebeansbeansjarsjarsandcrates

crates)

36

37start_point=start_point10

38

39print(Wecanalsodothatthisway)

40formula=secret_formula(start_point)

41thisisaneasywaytoapplyalisttoaformatstring

42print(Wedhavebeansjarsand

cratesformat(formula))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise24Session

$python36ex24py

Letspracticeeverything

Youdneedtoknowboutescapeswiththatdo

newlinesandtabs

--------------

Thelovelyworld

withlogicsofirmlyplanted

cannotdiscern

theneedsoflove

norcomprehendpassionfromintuition

andrequiresanexplanation

wherethereisnone

--------------

Thisshouldbefive5

Withastartingpointof10000

Wedhave5000000beans50000jarsand500crates

Wecanalsodothatthisway

Wedhave5000000beans5000jarsand50crates

StudyDrills1Makesuretodoyourchecksreaditbackwardreaditoutloudandputcommentsaboveconfusingparts

2BreakthefileonpurposethenrunittoseewhatkindsoferrorsyougetMakesureyoucanfixit

CommonStudentQuestionsWhydoyoucallthevariablejelly_beansbutthenamebeanslaterThatrsquospartofhowafunctionworksRememberthatinsidethefunctionthevariableistemporaryWhenyoureturnitthenitcanbeassignedtoavariableforlaterIrsquomjustmakinganewvariablenamedbeanstoholdthereturnvalue

WhatdoyoumeanbyreadingthecodebackwardStartatthelastlineComparethatlineinyourfiletothesamelineinmineOnceitrsquosexactlythesamemoveuptothenextlineDothisuntilyougettothefirstlineofthefile

WhowrotethatpoemIdidNotallofmypoemssuck

Exercise25EvenMorePractice

WersquoregoingtodosomemorepracticeinvolvingfunctionsandvariablestomakesureyouknowthemwellThisexerciseshouldbestraightforwardforyoutotypeinbreakdownandunderstandHoweverthisexerciseisalittledifferentYouwonrsquotberunningitInsteadyouwillimportitintoPythonandrunthefunctionsyourselfClickheretoviewcodeimage

ex25py

1defbreak_words(stuff)

2Thisfunctionwillbreakupwordsforus

3words=stuffsplit()

4returnwords

5

6defsort_words(words)

7Sortsthewords

8returnsorted(words)

9

10defprint_first_word(words)

11Printsthefirstwordafterpoppingitoff

12word=wordspop(0)

13print(word)

14

15defprint_last_word(words)

16Printsthelastwordafterpoppingitoff

17word=wordspop(-1)

18print(word)

19

20defsort_sentence(sentence)

21Takesinafullsentenceandreturnsthesorted

words

22words=break_words(sentence)

23returnsort_words(words)

24

25defprint_first_and_last(sentence)

26Printsthefirstandlastwordsofthesentence

27words=break_words(sentence)

28print_first_word(words)

29print_last_word(words)

30

31defprint_first_and_last_sorted(sentence)

32Sortsthewordsthenprintsthefirstandlastone

33words=sort_sentence(sentence)

34print_first_word(words)

35print_last_word(words)Firstrunthiswithpython36

ex25pytofindanyerrorsyouhavemadeOnceyouhavefoundallof

theerrorsyoucanandfixedthemyouwillthenwanttofollowthe

WhatYouShouldSeesectiontocompletetheexercise

WhatYouShouldSeeInthisexercisewersquoregoingtointeractwithyourex25pyfileinsidethepython36interpreteryouusedperiodicallytodocalculationsYourunpython36fromtheTerminallikethisClickheretoviewcodeimage

$python36

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtYouroutputshouldlooklikemineandafterthegtcharacter

(calledtheprompt)youcantypePythoncodeinanditwillrun

immediatelyUsingthisIwantyoutotypeeachoftheselinesof

Pythoncodeintopython36andseewhatitdoesClickheretoview

codeimage

Exercise25PythonSession

1importex25

2sentence=Allgoodthingscometothosewhowait

3words=ex25break_words(sentence)

4words

5sorted_words=ex25sort_words(words)

6sorted_words

7ex25print_first_word(words)

8ex25print_last_word(words)

9words

10ex25print_first_word(sorted_words)

11ex25print_last_word(sorted_words)

12sorted_words

13sorted_words=ex25sort_sentence(sentence)

14sorted_words

15ex25print_first_and_last(sentence)

16ex25print_first_and_last_sorted(sentence)Herersquoswhatitlooks

likewhenIworkwiththeex25pymoduleinpython36Clickhereto

viewcodeimage

Exercise25PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtimportex25

gtgtgtsentence=Allgoodthingscometothosewhowait

gtgtgtwords=ex25break_words(sentence)

gtgtgtwords

[Allgoodthingscometothosewhowait]

gtgtgtsorted_words=ex25sort_words(words)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_word(words)

All

gtgtgtex25print_last_word(words)

wait

gtgtgtwords

[goodthingscometothosewho]

gtgtgtex25print_first_word(sorted_words)

All

gtgtgtex25print_last_word(sorted_words)

who

gtgtgtsorted_words

[comegoodthingsthosetowait]

gtgtgtsorted_words=ex25sort_sentence(sentence)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_and_last(sentence)

All

wait

gtgtgtex25print_first_and_last_sorted(sentence)

All

whoAsyougothrougheachoftheselinesmakesureyoucanfindthe

functionthatrsquosbeingruninex25pyandunderstandhoweachone

worksIfyougetdifferentresultsorerroryoursquollhavetogofix

yourcodeexitpython36andstartover

StudyDrills1TaketheremaininglinesoftheWhatYouShouldSeeoutputandfigureoutwhattheyaredoingMakesureyouunderstandhowyouarerunningyourfunctionsintheex25module

2Trydoingthishelp(ex25)andalsohelp(ex25break_words)Noticehowyougethelpforyourmoduleandhowthehelpisthoseoddstringsyouputaftereachfunctioninex25Thosespecialstringsarecalleddocumentationcommentsandwersquollbeseeingmoreofthem

3Typingex25isannoyingAshortcutistodoyourimportlikethisfromex25importThisislikesayingldquoImporteverythingfromex25rdquoProgrammerslikesayingthingsbackwardStartanewsessionandseehowallyourfunctionsarerightthere

4TrybreakingyourfileandseewhatitlookslikeinpythonwhenyouuseitYouwillhavetoquitpythonwithquit()tobeabletoreloadit

CommonStudentQuestionsIgetNoneprintedoutforsomeofthefunctionsYouprobablyhaveafunctionthatismissingthereturnattheendGobackwardthroughthefileandconfirmthateverylineisright

Iget-bashimportcommandnotfoundwhenItypeimportex25PayattentiontowhatIrsquomdoingintheWhatYouShouldSeesectionIrsquomdoingthisinPythonnotintheTerminalThatmeansyoufirstrunPython

IgetImportErrorNomodulenamedex25pywhenItypeimportex25pyDonrsquotaddthepytotheendPythonknowsthefileendsinpysoyoujusttypeimportex25

IgetSyntaxErrorinvalidsyntaxwhenIrunthisThatmeansyouhavesomethinglikeamissing(ororsimilarsyntaxerroronthatlineoraboveitAnytimeyougetthaterrorstartatthelineitmentionsandcheckthatitrsquosrightthengobackwardcheckingeachlineabovethat

HowcanthewordspopfunctionchangethewordsvariableThatrsquosacomplicatedquestionbutinthiscasewordsisalistandbecauseofthatyoucangiveitcommandsanditrsquollretaintheresultsofthosecommandsThisissimilartohowfilesandmanyotherthingsworkedwhenyouwereworkingwiththem

WhenshouldIprintinsteadofreturninafunctionThereturnfromafunctiongivesthelineofcodethatcalledthefunctionaresultYoucanthinkofafunctionastakinginputthroughitsargumentsandreturningoutputthroughreturnTheprintiscompletelyunrelatedtothisandonlydealswithprintingoutputtotheTerminal

Exercise26CongratulationsTakeaTest

YouarealmostdonewiththefirsthalfofthebookThesecondhalfiswherethingsgetinterestingYouwilllearnlogicandbeabletodousefulthingslikemakedecisionsBeforeyoucontinueIhaveaquizforyouThisquizwillbeveryhardbecauseitrequiresyoutofixsomeoneelsersquoscodeWhenyouareaprogrammeryouoftenhavetodealwithotherprogrammersrsquocodemdashandalsowiththeirarroganceProgrammerswillveryfrequentlyclaimthattheircodeisperfectTheseprogrammersarestupidpeoplewhocarelittleforothersAgoodprogrammerassumeslikeagoodscientistthattherersquosalwayssomeprobabilitytheircodeiswrongGoodprogrammersstartfromthepremisethattheirsoftwareisbrokenandthenworktoruleoutallpossiblewaysitcouldbewrongbeforefinallyadmittingthatmaybeitreallyistheotherguyrsquoscodeInthisexerciseyouwillpracticedealingwithabadprogrammerbyfixingabadprogrammerrsquoscodeIhavepoorlycopiedExercises24and25intoafileandremovedrandomcharactersandaddedflawsMostoftheerrorsarethingsPythonwilltellyouwhilesomeofthemarematherrorsyoushouldfindOthersareformattingerrorsorspellingmistakesinthestringsAlloftheseerrorsareverycommonmistakesallprogrammersmakemdashevenexperiencedonesYourjobinthisexerciseistocorrectthisfileUseallofyourskillstomakethisfilebetterAnalyzeitfirstmaybeprintingitouttoedititlikeyouwouldaschooltermpaperFixeachflawandkeeprunningitandfixingituntilthescriptrunsperfectlyTrynottogethelpIfyougetstucktakeabreakandcomebacktoitlaterEvenifthistakesdaystodobustthroughitandmakeitrightThepointofthisexerciseisnrsquottotypeitinbuttofixanexistingfileTodothatyoumustgotohttplearnpythonthehardwayorgpython3exercise26txtCopy-pastethecodeintoafilenamedex26pyThisistheonlytimeyouareallowedtocopy-paste

CommonStudentQuestionsDoIhavetoimportex25pyorcanIjustremovethereferencestoitYoucandoeitherThisfilehasthefunctionsfromex25

thoughsofirstgowithremovingreferencestoitCanIrunthecodewhileIrsquomfixingitYoumostcertainlymayThecomputeristheretohelpsouseitasmuchaspossible

Exercise27MemorizingLogic

TodayisthedayyoustartlearningaboutlogicUptothispointyouhavedoneeverythingyoupossiblycanreadingandwritingfilestotheTerminalandhavelearnedquitealotofthemathcapabilitiesofPythonFromnowonyouwillbelearninglogicYouwonrsquotlearncomplextheoriesthatacademicslovetostudybutjustthebasiclogicthatmakesrealprogramsworkandthatrealprogrammersneedeverydayLearninglogichastocomeafteryoudosomememorizationIwantyoutodothisexerciseforanentireweekDonotfalterEvenifyouareboredoutofyourmindkeepdoingitThisexercisehasasetoflogictablesyoumustmemorizetomakeiteasierforyoutodothelaterexercisesIrsquomwarningyouthiswonrsquotbefunatfirstItwillbedownrightboringandtediousbutthisteachesyouaveryimportantskillyouwillneedasaprogrammerYouwillneedtobeabletomemorizeimportantconceptsinyourlifeMostoftheseconceptswillbeexcitingonceyougetthemYouwillstrugglewiththemlikewrestlingasquidthenonedayyouwillunderstanditAllthatworkmemorizingthebasicspaysoffbiglaterHerersquosatiponhowtomemorizesomethingwithoutgoinginsaneDoatinybitatatimethroughoutthedayandmarkdownwhatyouneedtoworkonmostDonottrytositdownfortwohoursstraightandmemorizethesetablesThiswonrsquotworkYourbrainwillonlyretainwhateveryoustudiedinthefirst15or30minutesanywayInsteadcreateabunchofindexcardswitheachcolumnontheleft(TrueorFalse)onthefrontandthecolumnontherightonthebackYoushouldthentakethemoutseetheldquoTrueorFalserdquoandimmediatelysayldquoTruerdquoKeeppracticinguntilyoucandothisOnceyoucandothatstartwritingoutyourowntruthtableseachnightintoanotebookDonotjustcopythemTrytodothemfrommemoryWhenyougetstuckglancequicklyattheonesIhaveheretorefreshyourmemoryDoingthiswilltrainyourbraintorememberthewholetableDonotspendmorethanoneweekonthisbecauseyouwillbeapplyingitasyougo

TheTruthTermsInPythonwehavethefollowingterms(charactersandphrases)fordeterminingifsomethingisldquoTruerdquoorldquoFalserdquoLogiconacomputerisallaboutseeingifsomecombinationofthesecharactersandsomevariablesisTrueatthatpointin

somecombinationofthesecharactersandsomevariablesisTrueatthatpointintheprogram

bullandbullorbullnotbull=(notequal)bull==(equal)bullgt=(greater-than-equal)bulllt=(less-than-equal)bullTruebullFalse

YouactuallyhaverunintothesecharactersbeforebutmaybenotthetermsTheterms(andornot)actuallyworkthewayyouexpectthemtojustlikeinEnglish

TheTruthTablesWewillnowusethesecharacterstomakethetruthtablesyouneedtomemorize

NowusethesetablestowriteupyourowncardsandspendtheweekmemorizingthemRememberthoughthereisnofailinginthisbookjusttryingashardasyoucaneachdayandthenalittlebitmore

CommonStudentQuestionsCanrsquotIjustlearntheconceptsbehindBooleanalgebraandnotmemorizethisSureyoucandothatbutthenyoursquollhavetoconstantlygothroughtherulesforBooleanalgebrawhileyoucodeIfyoumemorizethesefirstitnotonlybuildsyourmemorizationskillsitalsomakestheseoperationsnaturalAfterthattheconceptofBooleanalgebraiseasyButdowhateverworksforyou

Exercise28BooleanPractice

ThelogiccombinationsyoulearnedfromthelastexercisearecalledBooleanlogicexpressionsBooleanlogicisusedeverywhereinprogrammingItisafundamentalpartofcomputationandknowingtheexpressionsisakintoknowingyourscalesinmusicInthisexerciseyouwilltakethelogicexercisesyoumemorizedandstarttryingthemoutinPythonTakeeachoftheselogicproblemsandwritewhatyouthinktheanswerwillbeIneachcaseitwillbeeitherTrueorFalseOnceyouhavetheanswerswrittendownstartPythoninyourTerminalandtypeeachlogicproblemintoconfirmyouranswers

1TrueandTrue2FalseandTrue31==1and2==14test==test51==1or2=16Trueand1==17Falseand0=08Trueor1==19test==testing101=0and2==111test=testing12test==113not(TrueandFalse)14not(1==1and0=1)15not(10==1or1000==1000)16not(1=10or3==4)17not(testing==testingandZed==CoolGuy)

181==1and(not(testing==1or1==0))19chunky==baconand(not(3==4or3==3))203==3and(not(testing==testingor

Python==Fun))

IwillalsogiveyouatricktohelpyoufigureoutthemorecomplicatedonestowardtheendWheneveryouseetheseBooleanlogicstatementsyoucansolvethemeasilybythissimpleprocess1Findanequalitytest(==or=)andreplaceitwithitstruth

2Findeachandorinsideparenthesesandsolvethosefirst3Findeachnotandinvertit4Findanyremainingandorandsolveit5WhenyouaredoneyoushouldhaveTrueorFalse

Iwilldemonstratewithavariationonitem20Clickheretoviewcodeimage

3=4andnot(testing=testorPython==Python)

HerersquosmegoingthrougheachofthestepsandshowingyouthetranslationuntilIrsquoveboileditdowntoasingleresult1Solveeachequalitytest

3=4isTrueTrueandnot(testing=testorPython==Python)

testing=testisTrueTrueandnot(TrueorPython==Python)

Python==PythonTrueandnot(TrueorTrue)2Findeachandorinparentheses()(TrueorTrue)isTrueTrueandnot(True)

3Findeachnotandinvertitnot(True)isFalseTrueandFalse4FindanyremainingandorsandsolvethemTrueandFalseisFalse

WiththatwersquoredoneandknowtheresultisFalse

WarningThemorecomplicatedonesmayseemveryhardatfirstYoushouldbeabletotakeagoodfirststabatsolvingthembutdonotgetdiscouragedIrsquomjustgettingyouprimedformoreoftheseldquologicgymnasticsrdquosothatlatercoolstuffismucheasierJuststickwithitandkeeptrackofwhatyougetwrongbutdonotworrythatitrsquosnotgettinginyourheadquiteyetItrsquollcome

WhatYouShouldSeeAfteryouhavetriedtoguessatthesethisiswhatyoursessionwithPythonmightlooklikeClickheretoviewcodeimage

$python36

Python251(r25154863Feb62009190212)

[GCC401(AppleIncbuild5465)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtTrueandTrue

True

gtgtgt1==1and2==2

True

StudyDrills1TherearealotofoperatorsinPythonsimilarto=and==TrytofindasmanyldquoequalityoperatorsrdquoasyoucanTheyshouldbelikeltorlt=

2WriteoutthenamesofeachoftheseequalityoperatorsForexampleIcall=ldquonotequalrdquo

3PlaywithPythonbytypingoutnewBooleanoperatorsandbeforeyoupressEntertrytoshoutoutwhatitisDonotthinkaboutitShoutthefirstthingthatcomestomindWriteitdownthenpressEnterandkeeptrackofhowmanyyougetrightandwrong

4Throwawaythepieceofpaperfrom3soyoudonotaccidentallytrytouseitlater

CommonStudentQuestionsWhydoestestandtestreturntestor1and1return1insteadofTruePythonandmanylanguagesliketoreturnoneoftheoperandstotheirBooleanexpressionsratherthanjustTrueorFalseThismeansthatifyoudidFalseand1yougetthefirstoperand(False)butifyoudoTrueand1yougetthesecond(1)Playwiththisabit

Isthereanydifferencebetween=andltgtPythonhasdeprecatedltgtinfavorof=souse=Otherthanthatthereshouldbenodifference

IsnrsquotthereashortcutYesAnyandexpressionthathasaFalseisimmediatelyFalsesoyoucanstopthereAnyorexpressionthathasaTrueisimmediatelyTruesoyoucanstopthereButmakesurethatyoucanprocessthewholeexpressionbecauselateritbecomeshelpful

Exercise29WhatIf

HereisthenextscriptofPythonyouwillenterwhichintroducesyoutotheif-statementTypethisinmakeitrunexactlyrightandthenwersquollseeifyourpracticehaspaidoffClickheretoviewcodeimage

ex29py

1people=20

2cats=30

3dogs=15

4

5

6ifpeopleltcats

7print(ToomanycatsTheworldisdoomed)

8

9ifpeoplegtcats

10print(NotmanycatsTheworldissaved)

11

12ifpeopleltdogs

13print(Theworldisdrooledon)

14

15ifpeoplegtdogs

16print(Theworldisdry)

17

18

19dogs+=5

20

21ifpeoplegt=dogs

22print(Peoplearegreaterthanorequaltodogs)

23

24ifpeoplelt=dogs

25print(Peoplearelessthanorequaltodogs)

26

27

28ifpeople==dogs

29print(Peoplearedogs)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise29Session

$python36ex29py

ToomanycatsTheworldisdoomed

Theworldisdry

Peoplearegreaterthanorequaltodogs

Peoplearelessthanorequaltodogs

Peoplearedogs

StudyDrillsInthisStudyDrilltrytoguesswhatyouthinktheif-statementisandwhatitdoesTrytoanswerthesequestionsinyourownwordsbeforemovingontothenextexercise

1Whatdoyouthinktheifdoestothecodeunderit2Whydoesthecodeundertheifneedtobeindentedfourspaces3Whathappensifitisnrsquotindented4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryit

5Whathappensifyouchangetheinitialvaluesforpeoplecatsanddogs

CommonStudentQuestionsWhatdoes+=meanThecodex+=1isthesameasdoingx=x+1butinvolveslesstypingYoucancallthistheldquoincrementbyrdquooperatorThesamegoesfor-=andmanyotherexpressionsyoursquolllearnlater

Exercise30ElseandIf

Inthelastexerciseyouworkedoutsomeif-statementsandthentriedtoguesswhattheyareandhowtheyworkBeforeyoulearnmoreIrsquollexplainwhateverythingisbyansweringthequestionsyouhadfromthepreviousStudyDrillssectionYoudidtheStudyDrillsright

1WhatdoyouthinktheifdoestothecodeunderitAnif-statementcreateswhatiscalledaldquobranchrdquointhecodeItrsquoskindoflikethosechooseyourownadventurebookswhereyouareaskedtoturntoonepageifyoumakeonechoiceandanotherifyougoadifferentdirectionTheif-statementtellsyourscriptldquoIfthisBooleanexpressionisTruethenrunthecodeunderitotherwiseskipitrdquo

2WhydoesthecodeundertheifneedtobeindentedfourspacesAcolonattheendofalineishowyoutellPythonyouaregoingtocreateanewldquoblockrdquoofcodeandthenindentingfourspacestellsPythonwhatlinesofcodeareinthatblockThisisexactlythesamethingyoudidwhenyoumadefunctionsinthefirsthalfofthebook

3WhathappensifitisnrsquotindentedIfitisnrsquotindentedyouwillmostlikelycreateaPythonerrorPythonexpectsyoutoindentsomethingafteryouendalinewitha(colon)

4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryitYesyoucanandtheycanbeascomplexasyoulikealthoughreallycomplexthingsgenerallyarebadstyle

5WhathappensifyouchangetheinitialvaluesforpeoplecatsanddogsBecauseyouarecomparingnumbersifyouchangethenumbersdifferentif-statementswillevaluatetoTrueandtheblocksofcodeunderthemwillrunGobackandputdifferentnumbersinandseeifyoucanfigureoutinyourheadwhichblocksofcodewillrun

ComparemyanswerstoyouranswersandmakesureyoureallyunderstandtheconceptofaldquoblockrdquoofcodeThisisimportantforwhenyoudothenextexercisewhereyouwriteallthepartsofif-statementsthatyoucanuseTypethisoneinandmakeitworktooClickheretoviewcodeimage

ex30py

1people=30

2cars=40

3trucks=15

4

5

6ifcarsgtpeople

7print(Weshouldtakethecars)

8elifcarsltpeople

9print(Weshouldnottakethecars)

10else

11print(Wecantdecide)

12

13iftrucksgtcars

14print(Thatstoomanytrucks)

15eliftrucksltcars

16print(Maybewecouldtakethetrucks)

17else

18print(Westillcantdecide)

19

20ifpeoplegttrucks

21print(Alrightletsjusttakethetrucks)

22else

23print(Fineletsstayhomethen)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise30Session

$python36ex30py

Weshouldtakethecars

Maybewecouldtakethetrucks

Alrightletsjusttakethetrucks

StudyDrills1Trytoguesswhatelifandelsearedoing2Changethenumbersofcarspeopleandtrucksandthentracethrougheachif-statementtoseewhatwillbeprinted

3TrysomemorecomplexBooleanexpressionslikecarsgtpeopleortrucksltcars

4Aboveeachlinewriteacommentdescribingwhatthelinedoes

CommonStudentQuestions

CommonStudentQuestionsWhathappensifmultipleelifblocksareTruePythonstartsatthetopandrunsthefirstblockthatisTruesoitwillrunonlythefirstone

Exercise31MakingDecisions

InthefirsthalfofthisbookyoumostlyjustprintedoutstringsandcalledfunctionsbuteverythingwasbasicallyinastraightlineYourscriptsranstartingatthetopandwenttothebottomwheretheyendedIfyoumadeafunctionyoucouldrunthatfunctionlaterbutitstilldidnrsquothavethekindofbranchingyouneedtoreallymakedecisionsNowthatyouhaveifelseandelifyoucanstarttomakescriptsthatdecidethingsInthelastscriptyouwroteoutasimplesetoftestsaskingsomequestionsInthisscriptyouwillasktheuserquestionsandmakedecisionsbasedontheiranswersWritethisscriptandthenplaywithitquitealottofigureitoutClickheretoviewcodeimage

ex31py

1print(Youenteradarkroomwithtwodoors

2Doyougothroughdoor1ordoor2)

3

4door=input(gt)

5

6ifdoor==1

7print(Theresagiantbearhereeatingacheesecake)

8print(Whatdoyoudo)

9print(1Takethecake)

10print(2Screamatthebear)

11

12bear=input(gt)

13

14ifbear==1

15print(ThebeareatsyourfaceoffGoodjob)

16elifbear==2

17print(ThebeareatsyourlegsoffGoodjob)

18else

19print(fWelldoingbearisprobablybetter)

20print(Bearrunsaway)

21

22elifdoor==2

23print(YoustareintotheendlessabyssatCthulhus

retina)

24print(1Blueberries)

25print(2Yellowjacketclothespins)

26print(3Understandingrevolversyellingmelodies)

27

28insanity=input(gt)

29

30ifinsanity==1orinsanity==2

31print(Yourbodysurvivespoweredbyamindofjello)

32print(Goodjob)

33else

34print(Theinsanityrotsyoureyesintoapoolof

muck)

35print(Goodjob)

36

37else

38print(YoustumblearoundandfallonaknifeanddieGood

job)Akeypointhereisthatyouarenowputtingtheif-statements

insideif-statementsascodethatcanrunThisisverypowerfuland

canbeusedtocreateldquonestedrdquodecisionswhereonebranchleadsto

anotherandanother

Makesureyouunderstandthisconceptofif-statementsinsideif-statementsInfactdotheStudyDrillstoreallynailit

WhatYouShouldSeeHereismeplayingthislittleadventuregameIdonotdosowellClickheretoviewcodeimage

Exercise31Session

$python36ex31py

Youenteradarkroomwithtwodoors

Doyougothroughdoor1ordoor2

gt1

Theresagiantbearhereeatingacheesecake

Whatdoyoudo

1Takethecake

2Screamatthebear

gt2

ThebeareatsyourlegsoffGoodjob

StudyDrills1MakenewpartsofthegameandchangewhatdecisionspeoplecanmakeExpandthegameoutasmuchasyoucanbeforeitgetsridiculous

2WriteacompletelynewgameMaybeyoudonrsquotlikethisonesomakeyourownThisisyourcomputerdowhatyouwant

CommonStudentQuestions

CommonStudentQuestionsCanyoureplaceelifwithasequenceofif-elsecombinationsYoucaninsomesituationsbutitdependsonhoweachifelseiswrittenItalsomeansthatPythonwillcheckeveryif-elsecombinationratherthanjustthefirstfalseoneslikeitwouldwithif-elif-elseTrytomakesomeofthesetofigureoutthedifferences

HowdoItellwhetheranumberisbetweenarangeofnumbersYouhavetwooptionsUse0ltxlt10or1lt=xlt10whichisclassicnotationorusexinrange(110)

WhatifIwantedmoreoptionsintheif-elif-elseblocksAddmoreelifblocksforeachpossiblechoice

Exercise32LoopsandLists

YoushouldnowbeabletodosomeprogramsthataremuchmoreinterestingIfyouhavebeenkeepingupyoushouldrealizethatnowyoucancombinealltheotherthingsyouhavelearnedwithif-statementsandBooleanexpressionstomakeyourprogramsdosmartthingsHoweverprogramsalsoneedtodorepetitivethingsveryquicklyWearegoingtouseafor-loopinthisexercisetobuildandprintvariouslistsWhenyoudotheexerciseyouwillstarttofigureoutwhattheyareIwonrsquottellyourightnowYouhavetofigureitoutBeforeyoucanuseafor-loopyouneedawaytostoretheresultsofloopssomewhereThebestwaytodothisiswithlistsAlistisexactlywhatthenamesaysacontainerofthingsthatareorganizedinorderfromfirsttolastItrsquosnotcomplicatedyoujusthavetolearnanewsyntaxFirstherersquoshowyoumakelistsClickheretoviewcodeimage

hairs=[brownblondred]

eyes=[brownbluegreen]

weights=[1234]

Youstartthelistwiththe[(leftbracket)whichldquoopensrdquothelistThenyouputeachitemyouwantinthelistseparatedbycommassimilartofunctionargumentsLastlyendthelistwitha](rightbracket)toindicatethatitrsquosoverPythonthentakesthislistandallitscontentsandassignsthemtothevariable

WarningThisiswherethingsgettrickyforpeoplewhocanrsquotcodeYourbrainhasbeentaughtthattheworldisflatRememberinthelastexercisewhereyouputif-statementsinsideif-statementsThatprobablymadeyourbrainhurtbecausemostpeopledonotponderhowtoldquonestrdquothingsinsidethingsInprogrammingnestedstructuresareallovertheplaceYouwillfindfunctionsthatcallotherfunctionsthathaveif-statementsthathavelistswithlistsinsidelistsIfyouseeastructurelikethisthatyoucanrsquotfigureouttakeoutapencilandpaperandbreakitdownmanuallybitbybituntilyouunderstandit

Wenowwillbuildsomelistsusingsomefor-loopsandprintthemoutClickheretoviewcodeimage

ex32py

1the_count=[12345]

2fruits=[applesorangespearsapricots]

3change=[1pennies2dimes3quarters]

4

5thisfirstkindoffor-loopgoesthroughalist

6fornumberinthe_count

7print(fThisiscountnumber)

8

9sameasabove

10forfruitinfruits

11print(fAfruitoftypefruit)

12

13alsowecangothroughmixedliststoo

14noticewehavetousesincewedontknowwhatsinit

15foriinchange

16print(fIgoti)

17

18wecanalsobuildlistsfirststartwithanemptyone

19elements=[]

20

21thenusetherangefunctiontodo0to5counts

22foriinrange(06)

23print(fAddingitothelist)

24appendisafunctionthatlistsunderstand

25elementsappend(i)

26

27nowwecanprintthemouttoo

28foriinelements

29print(fElementwasi)

WhatYouShouldSee

Exercise32Session

$python36ex32py

Thisiscount1

Thisiscount2

Thisiscount3

Thisiscount4

Thisiscount5

Afruitoftypeapples

Afruitoftypeoranges

Afruitoftypepears

Afruitoftypeapricots

Igot1

Igotpennies

Igot2

Igotdimes

Igot3

Igotquarters

Adding0tothelist

Adding1tothelist

Adding2tothelist

Adding3tothelist

Adding4tothelist

Adding5tothelist

Elementwas0

Elementwas1

Elementwas2

Elementwas3

Elementwas4

Elementwas5

StudyDrills1TakealookathowyouusedrangeLookuptherangefunctiontounderstandit

2Couldyouhaveavoidedthatfor-loopentirelyonline22andjustassignedrange(06)directlytoelements

3FindthePythondocumentationonlistsandreadaboutthemWhatotheroperationscanyoudotolistsbesidesappend

CommonStudentQuestionsHowdoyoumakea2-dimensional(2D)listThatrsquosalistinalistlikethis[[123][456]]

ArenrsquotlistsandarraysthesamethingThatdependsonthelanguageandtheimplementationInclassictermsalistisverydifferentfromanarraybecauseofhowtheyrsquoreimplementedInRubythoughtheycallthesearraysInPythontheycallthemlistsJustcalltheselistsfornowsincethatrsquoswhatPythoncallsthem

Whyisafor-loopabletouseavariablethatisnrsquotdefinedyetThevariableisdefinedbythefor-loopwhenitstartsinitializingittothecurrentelementoftheloopiterationeachtimethrough

Whydoesforiinrange(13)onlylooptwotimesinsteadofthreetimesTherange()functiononlydoesnumbersfromthefirsttothelastnotincludingthelastSoitstopsattwonotthreeintheprecedingThisturnsouttobethemostcommonwaytodothiskindofloop

Whatdoeselementsappend()doItsimplyappendstotheendofthelistOpenupthePythonshellandtryafewexampleswithalistyoumakeAnytimeyourunintothingslikethisalwaystrytoplaywiththeminteractivelyinthePythonshell

Exercise33WhileLoops

Nowtototallyblowyourmindwithanewloopthewhile-loopAwhile-loopwillkeepexecutingthecodeblockunderitaslongasaBooleanexpressionisTrueWaityouhavebeenkeepingupwiththeterminologyrightThatifwewritealineandenditwitha(colon)thenthattellsPythontostartanewblockofcodeThenweindentandthatrsquosthenewcodeThisisallaboutstructuringyourprogramssothatPythonknowswhatyoumeanIfyoudonotgetthatideathengobackanddosomemoreworkwithif-statementsfunctionsandthefor-loopuntilyougetitLateronwersquollhavesomeexercisesthatwilltrainyourbraintoreadthesestructuressimilartohowweburnedBooleanexpressionsintoyourbrainBacktowhile-loopsWhattheydoissimplydoatestlikeanif-statementbutinsteadofrunningthecodeblockoncetheyjumpbacktotheldquotoprdquowherethewhileisandrepeatAwhile-looprunsuntiltheexpressionisFalseHerersquostheproblemwithwhile-loopsSometimestheydonotstopThisisgreatifyourintentionistojustkeeploopinguntiltheendoftheuniverseOtherwiseyoualmostalwayswantyourloopstoendeventuallyToavoidtheseproblemstherearesomerulestofollow1Makesurethatyouusewhile-loopssparinglyUsuallyafor-loopisbetter

2ReviewyourwhilestatementsandmakesurethattheBooleantestwillbecomeFalseatsomepoint

3Whenindoubtprintoutyourtestvariableatthetopandbottomofthewhile-looptoseewhatitrsquosdoing

Inthisexerciseyoulearnthewhile-loopwhiledoingthesethreechecksClickheretoviewcodeimage

ex33py

1i=0

2numbers=[]

3

4whileilt6

5print(fAtthetopiisi)

6numbersappend(i)

7

8i=i+1

9print(Numbersnownumbers)

10print(fAtthebottomiisi)

11

12

13print(Thenumbers)

14

15fornuminnumbers

16print(num)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise33Session

$python36ex33py

Atthetopiis0

Numbersnow[0]

Atthebottomiis1

Atthetopiis1

Numbersnow[01]

Atthebottomiis2

Atthetopiis2

Numbersnow[012]

Atthebottomiis3

Atthetopiis3

Numbersnow[0123]

Atthebottomiis4

Atthetopiis4

Numbersnow[01234]

Atthebottomiis5

Atthetopiis5

Numbersnow[012345]

Atthebottomiis6

Thenumbers

0

1

2

3

4

5

StudyDrills

1Convertthiswhile-looptoafunctionthatyoucancallandreplace6inthetest(ilt6)withavariable

2Usethisfunctiontorewritethescripttotrydifferentnumbers3Addanothervariabletothefunctionargumentsthatyoucanpassinthatletsyouchangethe+1online8soyoucanchangehowmuchitincrementsby

4Rewritethescriptagaintousethisfunctiontoseewhateffectthathas5Writeittousefor-loopsandrangeDoyouneedtheincrementorinthemiddleanymoreWhathappensifyoudonotgetridofit

Ifatanytimeyouaredoingthisitgoescrazy(itprobablywill)justholddownCTRLandpressc(CTRL-c)andtheprogramwillabort

CommonStudentQuestionsWhatrsquosthedifferencebetweenafor-loopandawhile-loopAfor-loopcanonlyiterate(loop)ldquooverrdquocollectionsofthingsAwhile-loopcandoanykindofiteration(looping)youwantHoweverwhile-loopsarehardertogetrightandyounormallycangetmanythingsdonewithfor-loops

LoopsarehardHowdoIfigurethemoutThemainreasonpeopledonrsquotunderstandloopsisbecausetheycanrsquotfollowtheldquojumpingrdquothatthecodedoesWhenalooprunsitgoesthroughitsblockofcodeandattheenditjumpsbacktothetopTovisualizethisputprintstatementsallovertheloopprintingoutwhereintheloopPythonisrunningandwhatthevariablesaresettoatthosepointsWriteprintlinesbeforetheloopatthetopoftheloopinthemiddleandatthebottomStudytheoutputandtrytounderstandthejumpingthatrsquosgoingon

Exercise34AccessingElementsofLists

ListsareprettyusefulbutunlessyoucangetatthethingsinthemtheyarenrsquotallthatgoodYoucanalreadygothroughtheelementsofalistinorderbutwhatifyouwantsaythefifthelementYouneedtoknowhowtoaccesstheelementsofalistHerersquoshowyouwouldaccessthefirstelementofalistClickheretoviewcodeimage

animals=[beartigerpenguinzebra]

bear=animals[0]

Youtakealistofanimalsandthenyougetthefirst(1st)oneusing0HowdoesthatworkBecauseofthewaymathworksPythonstartsitslistsat0ratherthan1ItseemsweirdbuttherearemanyadvantagestothiseventhoughitismostlyarbitraryThebestwaytoexplainwhyisbyshowingyouthedifferencebetweenhowyouusenumbersandhowprogrammersusenumbersImagineyouarewatchingthefouranimalsinourlist([beartigerpenguinzebra])runinaraceTheycrossthefinishlineintheorderwehavetheminthislistTheracewasreallyexcitingbecausetheanimalsdidnrsquoteateachotherandsomehowmanagedtorunaraceYourfriendshowsuplateandwantstoknowwhowonDoesyourfriendsayldquoHeywhocameinzerothrdquoNohesaysldquoHeywhocameinfirstrdquoThisisbecausetheorderoftheanimalsisimportantYoucanrsquothavethesecondanimalwithoutthefirst(1st)animalandyoucanrsquothavethethirdwithoutthesecondItrsquosalsoimpossibletohavealdquozerothrdquoanimalsincezeromeansnothingHowcanyouhaveanothingwinaraceItjustdoesnrsquotmakesenseWecallthesekindsofnumbersldquoordinalrdquonumbersbecausetheyindicateanorderingofthingsProgrammershowevercanrsquotthinkthiswaybecausetheycanpickanyelementoutofalistatanypointToprogrammersthelistofanimalsismorelikeadeckofcardsIftheywantthetigertheygrabitIftheywantthezebratheycantakeittooThisneedtopullelementsoutoflistsatrandommeansthattheyneedawaytoindicateelementsconsistentlybyanaddressoranldquoindexrdquoandthebestwaytodothatistostarttheindicesat0TrustmeonthisthemathiswayeasierforthesekindsofaccessesThiskindofnumberisaldquocardinalrdquonumberandmeansyoucanpickatrandomsothereneedstobea0elementHowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourself

HowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourselfldquoIwantthethirdanimalrdquoyoutranslatethisldquoordinalrdquonumbertoaldquocardinalrdquonumberbysubtracting1Theldquothirdrdquoanimalisatindex2andisthepenguinYouhavetodothisbecauseyouhavespentyourwholelifeusingordinalnumbersandnowyouhavetothinkincardinalJustsubtract1andyoursquoregoodRememberordinal==ordered1stcardinal==cardsatrandom0LetrsquospracticethisTakethislistofanimalsandfollowtheexerciseswhereItellyoutowritedownwhatanimalyougetforthatordinalorcardinalnumberRememberifIsayldquofirstrdquoldquosecondrdquothenIrsquomusingordinalsosubtract1IfIgiveyoucardinal(likeldquoTheanimalat1rdquo)thenuseitdirectlyClickheretoviewcodeimage

animals=[bearpython36peacockkangaroowhale

platypus]

1Theanimalat12Thethird(3rd)animal3Thefirst(1st)animal4Theanimalat35Thefifth(5th)animal6Theanimalat27Thesixth(6th)animal8Theanimalat4

ForeachofthesewriteoutafullsentenceoftheformldquoThefirst(1st)animalisat0andisabearrdquoThensayitbackwardsldquoTheanimalat0isthe1stanimalandisabearrdquoUseyourPythontocheckyouranswers

StudyDrills1Withwhatyouknowofthedifferencebetweenthesetypesofnumberscanyouexplainwhytheyear2010inldquoJanuary12010rdquoreallyis2010andnot2009(Hintyoucanrsquotpickyearsatrandom)

2Writesomemorelistsandworkoutsimilarindexesuntilyoucantranslatethem

3UsePythontocheckyouranswers

Warning

ProgrammerswilltellyoutoreadthisguynamedDijkstraonthissubjectIrecommendyouavoidhiswritingsonthisunlessyouenjoybeingyelledatbysomeonewhostoppedprogrammingatthesametimeprogrammingstarted

Exercise35BranchesandFunctions

Youhavelearnedif-statementsfunctionsandlistsNowitrsquostimetobendyourmindTypethisinandseeifyoucanfigureoutwhatitrsquosdoingClickheretoviewcodeimage

ex35py

1fromsysimportexit

2

3defgold_room()

4print(ThisroomisfullofgoldHowmuchdoyoutake)

5

6choice=input(gt)

7if0inchoiceor1inchoice

8how_much=int(choice)

9else

10dead(Manlearntotypeanumber)

11

12ifhow_muchlt50

13print(Niceyourenotgreedyyouwin)

14exit(0)

15else

16dead(Yougreedybastard)

17

18

19defbear_room()

20print(Thereisabearhere)

21print(Thebearhasabunchofhoney)

22print(Thefatbearisinfrontofanotherdoor)

23print(Howareyougoingtomovethebear)

24bear_moved=False

25

26whileTrue

27choice=input(gt)

28

29ifchoice==takehoney

30dead(Thebearlooksatyouthenslapsyourface

off)

31elifchoice==tauntbearandnotbear_moved

32print(Thebearhasmovedfromthedoor)

33print(Youcangothroughitnow)

34bear_moved=True

35elifchoice==tauntbearandbear_moved

36dead(Thebeargetspissedoffandchewsyourleg

off)

37elifchoice==opendoorandbear_moved

38gold_room()

39else

40print(Igotnoideawhatthatmeans)

41

42

43defcthulhu_room()

44print(HereyouseethegreatevilCthulhu)

45print(Heitwhateverstaresatyouandyougoinsane)

46print(Doyoufleeforyourlifeoreatyourhead)

47

48choice=input(gt)

49

50iffleeinchoice

51start()

52elifheadinchoice

53dead(Wellthatwastasty)

54else

55cthulhu_room()

56

57

58defdead(why)

59print(whyGoodjob)

60exit(0)

61

62defstart()

63print(Youareinadarkroom)

64print(Thereisadoortoyourrightandleft)

65print(Whichonedoyoutake)

66

67choice=input(gt)

68

69ifchoice==left

70bear_room()

71elifchoice==right

72cthulhu_room()

73else

74dead(Youstumblearoundtheroomuntilyoustarve)

75

76

77start()

WhatYouShouldSeeHerersquosmeplayingthegameClickheretoviewcodeimage

Exercise35Session

$python36ex35py

Youareinadarkroom

Thereisadoortoyourrightandleft

Whichonedoyoutake

gtleft

Thereisabearhere

Thebearhasabunchofhoney

Thefatbearisinfrontofanotherdoor

Howareyougoingtomovethebear

gttauntbear

Thebearhasmovedfromthedoor

Youcangothroughitnow

gtopendoor

ThisroomisfullofgoldHowmuchdoyoutake

gt1000

YougreedybastardGoodjob

StudyDrills1Drawamapofthegameandhowyouflowthroughit2Fixallofyourmistakesincludingspellingmistakes3Writecommentsforthefunctionsyoudonotunderstand4AddmoretothegameWhatcanyoudotobothsimplifyandexpandit5Thegold_roomhasaweirdwayofgettingyoutotypeanumberWhatareallthebugsinthiswayofdoingitCanyoumakeitbetterthanwhatIrsquovewrittenLookathowint()worksforclues

CommonStudentQuestionsHelpHowdoesthisprogramworkWhenyougetstuckunderstandingapieceofcodesimplywriteanEnglishcommentaboveeverylineexplainingwhatthatlinedoesKeepyourcommentsshortandsimilartothecodeTheneitherdiagramhowthecodeworksorwriteaparagraphdescribingitIfyoudothatyoursquollgetit

WhydidyouwritewhileTrueThatmakesaninfiniteloopWhatdoesexit(0)doOnmanyoperatingsystemsaprogramcanabortwithexit(0)andthenumberpassedinwillindicateanerrorornotIfyoudoexit(1)thenitwillbeanerrorbutexit(0)willbeagoodexitThereasonitrsquosbackwardfromnormalBooleanlogic(with0==False)isthatyoucanusedifferentnumbersto

indicatedifferenterrorresultsYoucandoexit(100)foradifferenterrorresultthanexit(2)orexit(1)

Whyisinput()sometimeswrittenasinput(gt)Theparametertoinputisastringthatitshouldprintasapromptbeforegettingtheuserrsquosinput

Exercise36DesigningandDebugging

Nowthatyouknowif-statementsIrsquomgoingtogiveyousomerulesforfor-loopsandwhile-loopsthatwillkeepyououtoftroubleIrsquomalsogoingtogiveyousometipsondebuggingsothatyoucanfigureoutproblemswithyourprogramFinallyyouwilldesignalittlegamesimilartothelastexercisebutwithaslighttwist

Rulesforif-statements1Everyif-statementmusthaveanelse2IfthiselseshouldneverrunbecauseitdoesnrsquotmakesensethenyoumustuseadiefunctionintheelsethatprintsoutanerrormessageanddiesjustlikewedidinthelastexerciseThiswillfindmanyerrors

3Nevernestif-statementsmorethantwodeepandalwaystrytodothemonedeep

4Treatif-statementslikeparagraphswhereeachif-elif-elsegroupingislikeasetofsentencesPutblanklinesbeforeandafter

5YourBooleantestsshouldbesimpleIftheyarecomplexmovetheircalculationstovariablesearlierinyourfunctionanduseagoodnameforthevariable

IfyoufollowthesesimplerulesyouwillstartwritingbettercodethanmostprogrammersGobacktothelastexerciseandseeifIfollowedalloftheserulesIfnotfixmymistakes

WarningNeverbeaslavetotherulesinreallifeFortrainingpurposesyouneedtofollowtheserulestomakeyourmindstrongbutinreallifesometimestheserulesarejuststupidIfyouthinkaruleisstupidtrynotusingit

RulesforLoops1Useawhile-looponlytoloopforeverandthatmeansprobablyneverThisonlyappliestoPythonotherlanguagesaredifferent

2Useafor-loopforallotherkindsofloopingespeciallyifthereisa

fixedorlimitednumberofthingstoloopover

TipsforDebugging1DonotusealdquodebuggerrdquoAdebuggerislikedoingafull-bodyscanonasickpersonYoudonotgetanyspecificusefulinformationandyoufindawholelotofinformationthatdoesnrsquothelpandisjustconfusing

2Thebestwaytodebugaprogramistouseprinttoprintoutthevaluesofvariablesatpointsintheprogramtoseewheretheygowrong

3MakesurepartsofyourprogramsworkasyouworkonthemDonotwritemassivefilesofcodebeforeyoutrytorunthemCodealittlerunalittlefixalittle

HomeworkNowwriteagamesimilartotheonethatIcreatedinthelastexerciseItcanbeanykindofgameyouwantinthesameflavorSpendaweekonitmakingitasinterestingaspossibleForStudyDrillsuselistsfunctionsandmodules(rememberthosefromExercise13)asmuchaspossibleandfindasmanynewpiecesofPythonasyoucantomakethegameworkBeforeyoustartcodingyoumustdrawamapforyourgameCreatetheroomsmonstersandtrapsthattheplayermustgothroughonpaperbeforeyoucodeOnceyouhaveyourmaptrytocodeitupIfyoufindproblemswiththemapthenadjustitandmakethecodematchThebestwaytoworkonapieceofsoftwareisinsmallchunkslikethis

1OnasheetofpaperoranindexcardwritealistoftasksyouneedtocompletetofinishthesoftwareThisisyourto-dolist

2Picktheeasiestthingyoucandofromyourlist3WriteoutEnglishcommentsinyoursourcefileasaguideforhowyouwouldaccomplishthistaskinyourcode

4WritesomeofthecodeundertheEnglishcomments5Quicklyrunyourscriptsoseeifthatcodeworked6Keepworkinginacycleofwritingsomecoderunningittotestitandfixingituntilitworks

7CrossthistaskoffyourlistthenpickyournexteasiesttaskandrepeatThisprocesswillhelpyouworkonsoftwareinamethodicalandconsistentmannerAsyouworkupdateyourlistbyremovingtasksyoudonrsquotreallyneedandaddingonesyoudo

andaddingonesyoudo

Exercise37SymbolReview

ItrsquostimetoreviewthesymbolsandPythonwordsyouknowandpickupafewmoreforthenextfewlessonsIhavewrittenoutallthePythonsymbolsandkeywordsthatareimportanttoknowInthislessontakeeachkeywordandfirsttrytowriteoutwhatitdoesfrommemoryNextsearchonlineforitandseewhatitreallydoesThismaybedifficultbecausesomeofthesearedifficulttosearchforbuttryanywayIfyougetoneofthesewrongfrommemorymakeanindexcardwiththecorrectdefinitionandtrytoldquocorrectrdquoyourmemoryFinallyuseeachoftheseinasmallPythonprogramorasmanyasyoucangetdoneThegoalistofindoutwhatthesymboldoesmakesureyougotitrightcorrectitifyoudidnotthenuseittolockitin

Keywords

DataTypesFordatatypeswriteoutwhatmakesupeachoneForexamplewithstringswriteouthowyoucreateastringFornumberswriteoutafewnumbers

StringEscapeSequencesForstringescapesequencesusetheminstringstomakesuretheydowhatyouthinktheydo

OldStyleStringFormatsSamethingforstringformatsusetheminsomestringstoknowwhattheydoOlderPython2codeusestheseformattingcharacterstodowhatf-stringsdoTrythemoutasanalternative

OperatorsSomeofthesemaybeunfamiliartoyoubutlookthemupanywayFindoutwhattheydoandifyoustillcanrsquotfigureitoutsaveitforlater

SpendaboutaweekonthisbutifyoufinishfasterthatrsquosgreatThepointistotrytogetcoverageonallthesesymbolsandmakesuretheyarelockedinyourheadWhatrsquosalsoimportantistofindoutwhatyoudonotknowsoyoucanfixitlater

ReadingCodeNowfindsomePythoncodetoreadYoushouldbereadinganyPythoncodeyoucanandtryingtostealideasthatyoufindYouactuallyshouldhaveenoughknowledgetobeabletoreadbutmaybenotunderstandwhatthecodedoesWhatthislessonteachesishowtoapplythingsyouhavelearnedtounderstandotherpeoplersquoscodeFirstprintoutthecodeyouwanttounderstandYesprintitoutbecauseyoureyesandbrainaremoreusedtoreadingpaperthancomputerscreensMakesureyouprintafewpagesatatimeSecondgothroughyourprintoutandtakenotesonthefollowing

1Functionsandwhattheydo2Whereeachvariableisfirstgivenavalue3AnyvariableswiththesamenamesindifferentpartsoftheprogramThesemaybetroublelater

4Anyif-statementswithoutelseclausesAretheyright5Anywhile-loopsthatmightnotend6Anypartsofcodethatyoucanrsquotunderstandforwhateverreason

ThirdonceyouhaveallofthismarkeduptrytoexplainittoyourselfbywritingcommentsasyougoExplainthefunctionshowtheyareusedwhatvariablesareinvolvedandanythingyoucantofigurethiscodeoutLastonallofthedifficultpartstracethevaluesofeachvariablelinebylinefunctionbyfunctionInfactdoanotherprintoutandwriteinthemarginthevalueofeachvariablethatyouneedtoldquotracerdquoOnceyouhaveagoodideaofwhatthecodedoesgobacktothecomputerandreaditagaintoseeifyoufindnewthingsKeepfindingmorecodeanddoingthisuntilyoudonotneedtheprintoutsanymore

StudyDrills1Findoutwhataldquoflowchartrdquoisanddrawafew2Ifyoufinderrorsincodeyouarereadingtrytofixthemandsendtheauthoryourchanges

3AnothertechniqueforwhenyouarenotusingpaperistoputcommentswithyournotesinthecodeSometimesthesecouldbecometheactualcommentstohelpthenextperson

CommonStudentQuestionsHowwouldIsearchforthesethingsonlineSimplyputldquopython36rdquobeforeanythingyouwanttofindForexampletofindldquoyieldrdquosearchforldquopython36yieldrdquo

Exercise38DoingThingstoLists

YouhavelearnedaboutlistsWhenyoulearnedaboutwhile-loopsyouldquoappendedrdquonumberstotheendofalistandprintedthemoutTherewerealsoStudyDrillswhereyouweresupposedtofindalltheotherthingsyoucandotolistsinthePythondocumentationThatwasawhilebacksoreviewthosetopicsifyoudonotknowwhatIrsquomtalkingaboutFounditRememberitGoodWhenyoudidthisyouhadalistandyouldquocalledrdquothefunctionappendonitHoweveryoumaynotreallyunderstandwhatrsquosgoingonsoletrsquosseewhatwecandotolistsWhenyouwritemystuffappend(hello)youareactuallysettingoffachainofeventsinsidePythontocausesomethingtohappentothemystufflistHerersquoshowitworks1PythonseesyoumentionedmystuffandlooksupthatvariableItmighthavetolookbackwardtoseeifyoucreateditwith=ifitisafunctionargumentorifitrsquosaglobalvariableEitherwayithastofindmystufffirst

2Onceitfindsmystuffitreadsthe(period)operatorandstartstolookatvariablesthatareapartofmystuffSincemystuffisalistitknowsthatmystuffhasabunchoffunctions

3ItthenhitsappendandcomparesthenametoallthenamesthatmystuffsaysitownsIfappendisinthere(itis)thenPythongrabsthattouse

4NextPythonseesthe((openparenthesis)andrealizesldquoOhheythisshouldbeafunctionrdquoAtthispointitcalls(runsorexecutes)thefunctionjustlikenormalbutitcallsthefunctionwithanextraargument

5ThatextraargumentismystuffIknowweirdrightButthatrsquoshowPythonworkssoitrsquosbesttojustrememberitandassumethatrsquostheresultWhathappensattheendofallthisisafunctioncallthatlookslikeappend(mystuffhello)insteadofwhatyoureadwhichismystuffappend(hello)

ForthemostpartyoudonothavetoknowthatthisisgoingonbutithelpswhenyougeterrormessagesfromPythonlikethisClickheretoviewcodeimage

$python36

gtgtgtclassThing(object)

deftest(message)

print(message)

gtgtgta=Thing()

gtgtgtatest(hello)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

TypeErrortest()takesexactly1argument(2given)

gtgtgtWhatwasallthatWellthisismetypingintothePythonshell

andshowingyousomemagicYouhavenrsquotseenclassyetbutwersquollget

intothatlaterFornowyouseehowPythonsaidtest()takesexactly

1argument(2given)IfyouseethisitmeansthatPythonchanged

atest(hello)totest(ahello)andthatsomewheresomeonemessed

upanddidnrsquotaddtheargumentfora

ThismightbealottotakeinbutwersquoregoingtospendafewexercisesgettingthisconceptfirminyourbrainTokickthingsoffherersquosanexercisethatmixesstringsandlistsforallkindsoffunClickheretoviewcodeimage

ex38py

1ten_things=ApplesOrangesCrowsTelephoneLightSugar

2

3print(Waittherearenot10thingsinthatlistLetsfix

that)

4

5stuff=ten_thingssplit()

6more_stuff=[DayNightSongFrisbee

7CornBananaGirlBoy]

8

9whilelen(stuff)=10

10next_one=more_stuffpop()

11print(Addingnext_one)

12stuffappend(next_one)

13print(fTherearelen(stuff)itemsnow)

14

15print(Therewegostuff)

16

17print(Letsdosomethingswithstuff)

18

19print(stuff[1])

20print(stuff[-1])whoafancy

21print(stuffpop())

22print(join(stuff))whatcool

23print(join(stuff[35]))superstellar

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Waittherearenot10thingsinthatlistLetsfixthat

AddingBoy

Thereare7itemsnow

AddingGirl

Thereare8itemsnow

AddingBanana

Thereare9itemsnow

AddingCorn

Thereare10itemsnow

Therewego[ApplesOrangesCrowsTelephoneLight

SugarBoyGirlBananaCorn]

Letsdosomethingswithstuff

Oranges

Corn

Corn

ApplesOrangesCrowsTelephoneLightSugarBoyGirlBanana

TelephoneLight

WhatListsCanDoLetrsquossayyouwanttocreateacomputergamebasedonGoFishIfyoudonrsquotknowwhatGoFishistakethetimenowtogoreaduponitontheinternetTodothisyouwouldneedtohavesomewayoftakingtheconceptofaldquodeckofcardsrdquoandputtingitintoyourPythonprogramYouthenhavetowritePythoncodethatknowshowtoworkthisimaginaryversionofadeckofcardssothatapersonplayingyourgamethinksthatitrsquosrealevenifitisnrsquotWhatyouneedisaldquodeckofcardsrdquostructureandprogrammerscallthiskindofthingadatastructureWhatrsquosadatastructureIfyouthinkaboutitadatastructureisjustaformalwaytostructure(organize)somedata(facts)ItreallyisthatsimpleEventhoughsomedatastructurescangetinsanelycomplexalltheyareisjustawaytostorefactsinsideaprogramsoyoucanaccessthemindifferentwaysTheystructuredataIrsquollbegettingintothismoreinthenextexercisebutlistsareoneofthemostcommondatastructuresprogrammersuseAlistisanorderedlistofthingsyouwanttostoreandaccessrandomlyorlinearlybyanindexWhatRememberwhatIsaidthoughjustbecauseaprogrammersaidldquolistisalistrdquodoesnrsquotmeanthatitrsquosanymorecomplexthanwhatalistalreadyisintherealworldLetrsquoslookatthedeckofcardsasanexampleofalist1Youhaveabunchofcardswithvalues

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard3Youcantakecardsoffthetopthebottomorthemiddleatrandom4Ifyouwanttofindaspecificcardyouhavetograbthedeckandgothroughitoneatatime

LetrsquoslookatwhatIsaidldquoAnorderedlistrdquoYesdeckofcardsisinorderwithafirstandalast

ldquoofthingsyouwanttostorerdquoYescardsarethingsIwanttostoreldquoandaccessrandomlyrdquoYesIcangrabacardfromanywhereinthedeck

ldquoorlinearlyrdquoYesifIwanttofindaspecificcardIcanstartatthebeginningandgoinorder

ldquobyanindexrdquoAlmostsincewithadeckofcardsifItoldyoutogetthecardatindex19yoursquodhavetocountuntilyoufoundthatoneInourPythonliststhecomputercanjustjumprighttoanyindexyougiveit

ThatisallalistdoesandthisshouldgiveyouawaytofigureoutconceptsinprogrammingEveryconceptinprogrammingusuallyhassomerelationshiptotherealworldAtleasttheusefulonesdoIfyoucanfigureoutwhattheanalogintherealworldisthenyoucanusethattofigureoutwhatthedatastructureshouldbeabletodo

WhentoUseListsYouusealistwheneveryouhavesomethingthatmatchesthelistdatastructurersquosusefulfeatures

1IfyouneedtomaintainorderRememberthisislistedordernotsortedorderListsdonotsortforyou

2IfyouneedtoaccessthecontentsrandomlybyanumberRememberthisisusingcardinalnumbersstartingat0

3Ifyouneedtogothroughthecontentslinearly(firsttolast)Rememberthatrsquoswhatfor-loopsarefor

Thisiswhenyouusealist

StudyDrills1TakeeachfunctionthatiscalledandgothroughthestepsforfunctioncallstotranslatethemtowhatPythondoesForexamplemore_stuffpop()ispop(more_stuff)

2TranslatethesetwowaystoviewthefunctioncallsinEnglishForexamplemore_stuffpop()readsasldquoCallpoponmore_stuffrdquoMeanwhilepop(more_stuff)meansldquoCallpopwithargumentmore_stuffrdquoUnderstandhowtheyarereallythesamething

3Goreadaboutobject-orientedprogrammingonlineConfusedIwastooDonotworryYouwilllearnenoughtobedangerousandyoucanslowlylearnmorelater

4ReaduponwhataclassisinPythonDonotreadabouthowotherlanguagesusethewordldquoclassrdquoThatwillonlymessyouup

5DonotworryIfyoudonothaveanyideawhatIrsquomtalkingaboutProgrammersliketofeelsmartsotheyinventedobject-orientedprogrammingnameditOOPandthenuseditwaytoomuchIfyouthinkthatrsquoshardyoushouldtrytouseldquofunctionalprogrammingrdquo

6Find10examplesofthingsintherealworldthatwouldfitinalistTrywritingsomescriptstoworkwiththem

CommonStudentQuestionsDidnrsquotyousaytonotusewhile-loopsYessojustremembersometimesyoucanbreaktherulesifyouhaveagoodreasonOnlyidiotsareslavestorulesallthetime

Whydoesjoin(stuff)notworkThewaythedocumentationforjoiniswrittendoesnrsquotmakesenseItdoesnotworklikethatandisinsteadamethodyoucallontheinsertedstringtoputbetweenthelisttobejoinedRewriteitlikejoin(stuff)

Whydidyouuseawhile-loopTryrewritingitwithafor-loopandseeifthatrsquoseasier

Whatdoesstuff[35]doThatextractsaldquoslicerdquofromthestufflistthatisfromelement3toelement4meaningitdoesnotincludeelement5Itrsquossimilartohowrange(35)wouldwork

Exercise39DictionariesOhLovelyDictionaries

YouarenowgoingtolearnabouttheDictionarydatastructureinPythonADictionary(ordict)isawaytostoredatajustlikealistbutinsteadofusingonlynumberstogetthedatayoucanusealmostanythingThisletsyoutreatadictlikeitrsquosadatabaseforstoringandorganizingdataLetrsquoscomparewhatdictscandotowhatlistscandoYouseealistletsyoudothisClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtthings=[abcd]

gtgtgtprint(things[1])

b

gtgtgtthings[1]=z

gtgtgtprint(things[1])

z

gtgtgtthings

[azcd]

YoucanusenumberstoindexintoalistmeaningyoucanusenumberstofindoutwhatrsquosinlistsYoushouldknowthisaboutlistsbynowbutmakesureyouunderstandthatyoucanonlyusenumberstogetitemsoutofalistAdictletsyouuseanythingnotjustnumbersYesadictassociatesonethingtoanothernomatterwhatitisTakealookClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtstuff=nameZedage39height612+2

gtgtgtprint(stuff[name])

Zed

gtgtgtprint(stuff[age])

39

gtgtgtprint(stuff[height])

74

gtgtgtstuff[city]=SF

gtgtgtprint(stuff[city])

SF

YouwillseethatinsteadofjustnumberswersquoreusingstringstosaywhatwewantfromthestuffdictionaryWecanalsoputnewthingsintothedictionary

withstringsItdoesnrsquothavetobestringsthoughWecanalsodothisExercise39PythonSession

gtgtgtstuff[1]=Wow

gtgtgtstuff[2]=Neato

gtgtgtprint(stuff[1])

Wow

gtgtgtprint(stuff[2])

NeatoInthiscodeIusednumbersandthenyoucanseethereare

numbersandstringsaskeysinthedictwhenIprintitIcoulduse

anythingWellalmostbutjustpretendyoucanuseanythingfornow

OfcourseadictionarythatyoucanonlyputthingsinisprettystupidsoherersquoshowyoudeletethingswiththedelkeywordClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtdelstuff[city]

gtgtgtdelstuff[1]

gtgtgtdelstuff[2]

gtgtgtstuff

nameZedage39height74

ADictionaryExampleWersquollnowdoanexercisethatyoumuststudyverycarefullyIwantyoutotypethiscodeinandtrytounderstandwhatrsquosgoingonTakenoteofwhenyouputthingsinadictgetthemfromahashandalltheoperationsyouuseNoticehowthisexampleismappingstatestotheirabbreviationsandthentheabbreviationstocitiesinthestatesRemembermapping(orassociating)isthekeyconceptinadictionaryClickheretoviewcodeimage

ex39py

1createamappingofstatetoabbreviation

2states=

3OregonOR

4FloridaFL

5CaliforniaCA

6NewYorkNY

7MichiganMI

8

9

10createabasicsetofstatesandsomecitiesinthem

11cities=

12CASanFrancisco

13MIDetroit

14FLJacksonville

15

16

17addsomemorecities

18cities[NY]=NewYork

19cities[OR]=Portland

20

21printoutsomecities

22print(-10)

23print(NYStatehascities[NY])

24print(ORStatehascities[OR])

25

26printsomestates

27print(-10)

28print(Michigansabbreviationisstates[Michigan])

29print(Floridasabbreviationisstates[Florida])

30

31doitbyusingthestatethencitiesdict

32print(-10)

33print(Michiganhascities[states[Michigan]])

34print(Floridahascities[states[Florida]])

35

36printeverystateabbreviation

37print(-10)

38forstateabbrevinlist(statesitems())

39print(fstateisabbreviatedabbrev)

40

41printeverycityinstate

42print(-10)

43forabbrevcityinlist(citiesitems())

44print(fabbrevhasthecitycity)

45

46nowdobothatthesametime

47print(-10)

48forstateabbrevinlist(statesitems())

49print(fstatestateisabbreviatedabbrev)

50print(fandhascitycities[abbrev])

51

52print(-10)

53safelygetaabbreviationbystatethatmightnotbethere

54state=statesget(Texas)

55

56ifnotstate

57print(SorrynoTexas)

58

59getacitywithadefaultvalue

60city=citiesget(TXDoesNotExist)

61print(fThecityforthestateTXiscity)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise39Session

$python36ex39py

----------

NYStatehasNewYork

ORStatehasPortland

----------

MichigansabbreviationisMI

FloridasabbreviationisFL

----------

MichiganhasDetroit

FloridahasJacksonville

----------

OregonisabbreviatedOR

FloridaisabbreviatedFL

CaliforniaisabbreviatedCA

NewYorkisabbreviatedNY

MichiganisabbreviatedMI

----------

CAhasthecitySanFrancisco

MIhasthecityDetroit

FLhasthecityJacksonville

NYhasthecityNewYork

ORhasthecityPortland

----------

OregonstateisabbreviatedOR

andhascityPortland

FloridastateisabbreviatedFL

andhascityJacksonville

CaliforniastateisabbreviatedCA

andhascitySanFrancisco

NewYorkstateisabbreviatedNY

andhascityNewYork

MichiganstateisabbreviatedMI

andhascityDetroit

----------

SorrynoTexas

ThecityforthestateTXisDoesNotExist

WhatDictionariesCanDo

WhatDictionariesCanDoAdictionaryisanotherexampleofadatastructureandlikealistitisoneofthemostcommonlyuseddatastructuresinprogrammingAdictionaryisusedtomaporassociatethingsyouwanttostoretokeysyouneedtogetthemAgainprogrammersdonrsquotuseatermlikeldquodictionaryrdquoforsomethingthatdoesnrsquotworklikeanactualdictionaryfullofwordssoletrsquosusethatasourrealworldexampleLetrsquossayyouwanttofindoutwhatthewordldquohonorificabilitudinitatibusrdquomeansTodayyouwouldsimplycopy-pastethatwordintoasearchengineandthenfindouttheanswerandwecouldsayasearchengineislikeareallyhugesupercomplexversionoftheOxfordEnglishDictionary(OED)Beforesearchengineswhatyouwoulddoisthis1GotoyourlibraryandgetldquothedictionaryrdquoLetrsquossayitrsquostheOED

2YouknowldquohonorificabilitudinitatibusrdquostartswiththeletterldquoHrdquosoyoulookonthesideofthebookforthelittletabthathasldquoHrdquoonit

3Skimthepagesuntilyouareclosetowhereldquohonrdquostarts4SkimafewmorepagesuntilyoufindldquohonorificabilitudinitatibusrdquoorhitthebeginningoftheldquohprdquowordsandrealizethiswordisnrsquotintheOED

5Onceyoufindtheentryyoureadthedefinitiontofigureoutwhatitmeans

ThisprocessisnearlyexactlythewayadictworksandyouarebasicallyldquomappingrdquothewordldquohonorificabilitudinitatibusrdquotoitsdefinitionAdictinPythonisjustlikeadictionaryintherealworldsuchastheOED

StudyDrills1Dothissamekindofmappingwithcitiesandstatesregionsinyourcountryorsomeothercountry

2FindthePythondocumentationfordictionariesandtrytodoevenmorethingstothem

3FindoutwhatyoucanrsquotdowithdictionariesAbigoneisthattheydonothaveordersotryplayingwiththat

CommonStudentQuestionsWhatisthedifferencebetweenalistandadictionaryAlistisforanorderedlistofitemsAdictionary(ordict)isformatchingsomeitems(calledldquokeysrdquo)tootheritems(calledldquovaluesrdquo)

WhatwouldIuseadictionaryforWhenyouhavetotakeonevalueandldquolookuprdquoanothervalueInfactyoucouldcalldictionariesldquolookuptablesrdquo

WhatwouldIusealistforUsealistforanysequenceofthingsthatneedstobeinorderandyouonlyneedtolookthemupbyanumericindex

WhatifIneedadictionarybutIneedittobeinorderTakealookatthecollectionsOrderedDictdatastructureinPythonSearchforitonlinetofindthedocumentation

Exercise40ModulesClassesandObjects

Pythoniscalledanldquoobject-orientedprogramminglanguagerdquoThismeansthereisaconstructinPythoncalledaclassthatletsyoustructureyoursoftwareinaparticularwayUsingclassesyoucanaddconsistencytoyourprogramssothattheycanbeusedinacleanerwayAtleastthatrsquosthetheoryIamnowgoingtoteachyouthebeginningsofobject-orientedprogrammingclassesandobjectsusingwhatyoualreadyknowaboutdictionariesandmodulesMyproblemisthatobject-orientedprogramming(OOP)isjustplainweirdYouhavetostrugglewiththistrytounderstandwhatIsayheretypeinthecodeandinthenextexerciseIrsquollhammeritinHerewego

ModulesAreLikeDictionariesYouknowhowadictionaryiscreatedandusedandthatitisawaytomaponethingtoanotherThatmeansifyouhaveadictionarywithakeyldquoapplerdquoandyouwanttogetitthenyoudothisClickheretoviewcodeimage

ex40apy

1mystuff=appleIAMAPPLES

2print(mystuff[apple])

KeepthisideaofldquogetXfromYrdquoinyourheadandnowthinkaboutmodulesYoursquovemadeafewsofarandyoushouldknowtheyare1APythonfilewithsomefunctionsorvariablesinit

2Whichyoucanimport3Andaccessthefunctionsorvariablesofwiththe(dot)operator

ImagineIhaveamodulethatIdecidetonamemystuffpyandIputafunctioninitcalledappleHerersquosthemodulemystuffpyClickheretoviewcodeimage

ex40apy

1thisgoesinmystuffpy

2defapple()

3print(IAMAPPLES)OnceIhavethiscodeIcanusethe

moduleMyStuffwithimportandthenaccesstheapplefunction

ex40apy

1importmystuff

2mystuffapple()Icouldalsoputavariableinitnamed

tangerineClickheretoviewcodeimage

ex40apy

1defapple()

2print(IAMAPPLES)

3

4thisisjustavariable

5tangerine=Livingreflectionofadream

Icanaccessthatthesamewayex40apy

1importmystuff

2

3mystuffapple()

4print(mystufftangerine)Referbacktothedictionaryandyou

shouldstarttoseehowthisissimilartousingadictionarybut

thesyntaxisdifferentLetrsquoscompareClickheretoviewcodeimage

ex40apy

1mystuff[apple]getapplefromdict

2mystuffapple()getapplefromthemodule

3mystufftangerinesamethingitsjustavariableThismeans

wehaveaverycommonpatterninPython1Takeakey=valuestyle

container

2GetsomethingoutofitbythekeyrsquosnameInthecaseofthedictionarythekeyisastringandthesyntaxis[key]InthecaseofthemodulethekeyisanidentifierandthesyntaxiskeyOtherthanthattheyarenearlythesamething

ClassesAreLikeModulesYoucanthinkaboutamoduleasaspecializeddictionarythatcanstorePythoncodesoyoucanaccessitwiththeoperatorPythonalsohasanotherconstructthatservesasimilarpurposecalledaclassAclassisawaytotakeagroupingof

functionsanddataandplacetheminsideacontainersoyoucanaccessthemwiththe(dot)operatorIfIweretocreateaclassjustlikethemystuffmoduleIrsquoddosomethinglikethisClickheretoviewcodeimage

ex40apy

1classMyStuff(object)

2

3def__init__(self)

4selftangerine=Andnowathousandyearsbetween

5

6defapple(self)

7print(IAMCLASSYAPPLES)Thatlookscomplicated

comparedtomodulesandthereisdefinitelyalotgoingonby

comparisonbutyoushouldbeabletomakeouthowthisislikea

ldquomini-modulerdquowithMyStuffhavinganapple()functioninitWhatis

probablyconfusingisthe__init__()functionanduseof

selftangerineforsettingthetangerineinstancevariable

HerersquoswhyclassesareusedinsteadofmodulesYoucantakethisMyStuffclassanduseittocraftmanyofthemmillionsatatimeifyouwantandeachonewonrsquotinterferewitheachotherWhenyouimportamodulethereisonlyonefortheentireprogramunlessyoudosomemonsterhacksBeforeyoucanunderstandthisthoughyouneedtoknowwhatanldquoobjectrdquoisandhowtoworkwithMyStuffjustlikeyoudowiththemystuffpymodule

ObjectsAreLikeImportIfaclassislikealdquomini-modulerdquothentherehastobeaconceptsimilartoimportbutforclassesThatconceptiscalledldquoinstantiaterdquowhichisjustafancyobnoxiousoverlysmartwaytosayldquocreaterdquoWhenyouinstantiateaclasswhatyougetiscalledanobjectYouinstantiate(create)aclassbycallingtheclasslikeitrsquosafunctionlikethisex40apy

1thing=MyStuff()

2thingapple()

3print(thingtangerine)Thefirstlineistheldquoinstantiaterdquo

operationanditrsquosalotlikecallingafunctionHoweverPython

coordinatesasequenceofeventsforyoubehindthescenesIrsquollgo

throughthesestepsusingtheprecedingcodeforMyStuff1Python

looksforMyStuff()andseesthatitisaclassyoursquovedefined

2Pythoncraftsanemptyobjectwithallthefunctionsyoursquovespecifiedintheclassusingdef

3Pythonthenlookstoseeifyoumadealdquomagicrdquo__init__functionandifyouhaveitcallsthatfunctiontoinitializeyournewlycreatedemptyobject

4IntheMyStufffunction__init__youthengetthisextravariableselfwhichisthatemptyobjectPythonmadeforyouandyoucansetvariablesonitjustlikeyouwouldwithamoduledictionaryorotherobject

5Inthiscaseyousetselftangerinetoasonglyricandthenyoursquoveinitializedthisobject

6NowPythoncantakethisnewlymintedobjectandassignittothethingvariableforyoutoworkwith

ThatrsquosthebasicsofhowPythondoesthisldquomini-importrdquowhenyoucallaclasslikeafunctionRememberthatthisisnotgivingyoutheclassbutinsteadisusingtheclassasablueprintforbuildingacopyofthattypeofthingKeepinmindthatIrsquomgivingyouaslightlyinaccurateideaofhowtheseworksothatyoucanstarttobuildupanunderstandingofclassesbasedonwhatyouknowaboutmodulesThetruthisclassesandobjectssuddenlydivergefrommodulesatthispointIfIwerebeingtotallyhonestIrsquodsaysomethingmorelikethisbullClassesarelikeblueprintsordefinitionsforcreatingnewmini-modules

bullInstantiationishowyoumakeoneofthesemini-modulesandimportitatthesametimeldquoInstantiaterdquojustmeanstocreateanobjectfromtheclass

bullTheresultingcreatedmini-moduleiscalledanobjectandyouthenassignittoavariabletoworkwithit

Atthispointobjectsbehavedifferentlyfrommodulesandthisshouldonlyserveasawayforyoutobridgeovertounderstandingclassesandobjects

GettingThingsfromThingsInowhavethreewaystogetthingsfromthingsClickheretoviewcodeimage

ex40apy

1dictstyle

2mystuff[apples]

3

4modulestyle

5mystuffapples()

6print(mystufftangerine)

7

8classstyle

9thing=MyStuff()

10thingapples()

11print(thingtangerine)

AFirstClassExampleYoushouldstartseeingthesimilaritiesinthesethreekey=valuecontainertypesandprobablyhaveabunchofquestionsHangonwiththequestionsasthenextexercisewillhammerhomeyourldquoobject-orientedvocabularyrdquoInthisexerciseIjustwantyoutotypeinthiscodeandgetitworkingsothatyouhavesomeexperiencebeforemovingonClickheretoviewcodeimage

ex40py

1classSong(object)

2

3def__init__(selflyrics)

4selflyrics=lyrics

5

6defsing_me_a_song(self)

7forlineinselflyrics

8print(line)

9

10happy_bday=Song([Happybirthdaytoyou

11Idontwanttogetsued

12SoIllstoprightthere])

13

14bulls_on_parade=Song([Theyrallyaroundthafamily

15Withpocketsfullofshells])

16

17happy_bdaysing_me_a_song()

18

19bulls_on_paradesing_me_a_song()

WhatYouShouldSee

Exercise40Session

$python36ex40py

Happybirthdaytoyou

Idontwanttogetsued

SoIllstoprightthere

Theyrallyaroundthafamily

Withpocketsfullofshells

StudyDrills1Writesomemoresongsusingthisandmakesureyouunderstandthatyoursquorepassingalistofstringsasthelyrics

2Putthelyricsinaseparatevariablethenpassthatvariabletotheclasstouseinstead

3SeeifyoucanhackonthisandmakeitdomorethingsDonrsquotworryifyouhavenoideahowjustgiveitatryandseewhathappensBreakittrashitthrashityoucanrsquothurtit

4Searchonlineforldquoobject-orientedprogrammingrdquoandtrytooverflowyourbrainwithwhatyoureadDonrsquotworryifitmakesabsolutelynosensetoyouHalfofthatstuffmakesnosensetometoo

CommonStudentQuestionsWhydoIneedselfwhenImake__init__orotherfunctionsforclassesIfyoudonrsquothaveselfthencodelikecheese=FrankisambiguousThatcodeisnrsquotclearaboutwhetheryoumeantheinstancersquoscheeseattributeoralocalvariablenamedcheeseWithselfcheese=Frankitrsquosveryclearyoumeantheinstanceattributeselfcheese

Exercise41LearningtoSpeakObject-Oriented

InthisexerciseIrsquomgoingtoteachyouhowtospeakldquoobject-orientedrdquoWhatIrsquolldoisgiveyouasmallsetofwordswithdefinitionsyouneedtoknowThenIrsquollgiveyouasetofsentenceswithholesinthemthatyoursquollhavetounderstandFinallyIrsquomgoingtogiveyoualargesetofexercisesthatyouhavetocompletetomakethesesentencessolidinyourvocabulary

WordDrillsclassTellPythontomakeanewtypeofthingobjectTwomeaningsthemostbasictypeofthingandanyinstanceofsomething

instanceWhatyougetwhenyoutellPythontocreateaclassdefHowyoudefineafunctioninsideaclassselfInsidethefunctionsinaclassselfisavariablefortheinstanceobjectbeingaccessed

inheritanceTheconceptthatoneclasscaninherittraitsfromanotherclassmuchlikeyouandyourparents

compositionTheconceptthataclasscanbecomposedofotherclassesaspartsmuchlikehowacarhaswheels

attributeApropertyclasseshavethatarefromcompositionandareusuallyvariables

is-aAphrasetosaythatsomethinginheritsfromanotherasinaldquosalmonrdquois-ardquofishldquo

has-aAphrasetosaythatsomethingiscomposedofotherthingsorhasatraitasinldquoasalmonhas-amouthrdquo

TakesometimetomakeflashcardsforthesetermsandmemorizethemAsusualthiswonrsquotmaketoomuchsenseuntilafteryouarefinishedwiththisexercisebutyouneedtoknowthebasewordsfirst

PhraseDrillsNextIhavealistofPythoncodesnippetsontheleftandtheEnglishsentencesforthem

classX(Y)ldquoMakeaclassnamedXthatis-aYrdquo

classX(object)def__init__(selfJ)ldquoclassXhas-a__init__thattakesselfandJparametersrdquo

classX(object)defM(selfJ)ldquoclassXhas-afunctionnamedMthattakesselfandJparametersrdquo

foo=X()ldquoSetfootoaninstanceofclassXrdquofooM(J)ldquoFromfoogettheMfunctionandcallitwithparametersselfJrdquo

fooK=QldquoFromfoogettheKattributeandsetittoQrdquoIneachofthesewhereyouseeXYMJKQandfooyoucantreatthoselikeblankspotsForexampleIcanalsowritethesesentencesasfollows1ldquoMakeaclassnamedthatis-aYrdquo

2ldquoclasshas-a__init__thattakesselfandparametersrdquo3ldquoclasshas-afunctionnamedthattakesselfandparametersrdquo4ldquoSettoaninstanceofclassrdquo5ldquoFromgetthefunctionandcallitwithself=andparametersrdquo

6ldquoFromgettheattributeandsetittordquoAgainwritetheseonsomeflashcardsanddrillthemPutthePythoncodesnippetonthefrontandthesentenceonthebackYouhavetobeabletosaythesentenceexactlythesameeverytimewheneveryouseethatformNotsortofthesamebutexactlythesame

CombinedDrillsThefinalpreparationforyouistocombinethewordsdrillswiththephrasedrillsWhatIwantyoutodoforthisdrillisthis

1Takeaphrasecardanddrillit2Flipitoverandreadthesentenceandforeachwordinthesentencethatisinyourwordsdrillsgetthatcard

3Drillthosewordsforthatsentence4Keepgoinguntilyouareboredthentakeabreakanddoitagain

AReadingTestInowhavealittlePythonhackscriptthatwilldrillyouonthesewordsyouknowinaninfinitemannerThisisasimplescriptyoushouldbeabletofigureoutandtheonlythingitdoesisusealibrarycalledurllibtodownloadalist

ofwordsIhaveHerersquosthescriptwhichyoushouldenterintooop_testpytoworkwithitClickheretoviewcodeimage

ex41py

1importrandom

2fromurllibrequestimporturlopen

3importsys

4

5WORD_URL=httplearncodethehardwayorgwordstxt

6WORDS=[]

7

8PHRASES=

9class()

10Makeaclassnamedthatis-a

11class(object)ntdef__init__(self)

12classhas-a__init__thattakesselfand

params

13class(object)ntdef(self)

14classhas-afunctionthattakesselfand

params

15=()

16Settoaninstanceofclass

17()

18Fromgetthefunctioncallitwithparamsself

19=

20Fromgettheattributeandsetitto

21

22

23dotheywanttodrillphrasesfirst

24iflen(sysargv)==2andsysargv[1]==english

25PHRASE_FIRST=True

26else

27PHRASE_FIRST=False

28

29loadupthewordsfromthewebsite

30forwordinurlopen(WORD_URL)readlines()

31WORDSappend(str(wordstrip()encoding=utf-8))

32

33

34defconvert(snippetphrase)

35class_names=[wcapitalize()forwin

36randomsample(WORDSsnippetcount())]

37other_names=randomsample(WORDSsnippetcount())

38results=[]

39param_names=[]

40

41foriinrange(0snippetcount())

42param_count=randomrandint(13)

43param_namesappend(join(

44randomsample(WORDSparam_count)))

45

46forsentenceinsnippetphrase

47result=sentence[]

48

49fakeclassnames

50forwordinclass_names

51result=resultreplace(word1)

52

53fakeothernames

54forwordinother_names

55result=resultreplace(word1)

56

57fakeparameterlists

58forwordinparam_names

59result=resultreplace(word1)

60

61resultsappend(result)

62

63returnresults

64

65

66keepgoinguntiltheyhitCTRL-D

67try

68whileTrue

69snippets=list(PHRASESkeys())

70randomshuffle(snippets)

71

72forsnippetinsnippets

73phrase=PHRASES[snippet]

74questionanswer=convert(snippetphrase)

75ifPHRASE_FIRST

76questionanswer=answerquestion

77

78print(question)

79

80input(lt)

81print(fANSWERanswernn)

82exceptEOFError

83print(nBye)Runthisscriptandtrytotranslatethe

ldquoobject-orientedphrasesrdquointoEnglishtranslationsYoushouldsee

thatthePHRASESdicthasbothformsandthatyoujusthavetoenter

thecorrectone

PracticeEnglishtoCode

PracticeEnglishtoCodeNextyoushouldrunthescriptwiththeldquoenglishrdquooptionsothatyoudrilltheinverseoperation

$pythonoop_testpyenglishRememberthatthesephrasesareusing

nonsensewordsPartoflearningtoreadcodewellistostopplacing

somuchmeaningonthenamesusedforvariablesandclassesToo

oftenpeoplewillreadawordlikeldquoCorkrdquoandsuddenlygetderailed

becausethatwordwillconfusethemaboutthemeaningIntheabove

exampleldquoCorkrdquoisjustanarbitrarynamechosenforaclassDonrsquot

placeanyothermeaningonitandinsteadtreatitlikethepatterns

Irsquovegivenyou

ReadingMoreCodeYouarenowtogoonanewquesttoreadevenmorecodetoreadthephrasesyoujustlearnedinthecodeyoureadYouwilllookforallthefileswithclassesandthendothefollowing

1Foreachclassgiveitsnameandwhatotherclassesitinheritsfrom2Underthatlisteveryfunctionithasandtheparameterstheytake3Listalloftheattributesitusesonitsself4Foreachattributegivetheclassthisattributeis

ThegoalistogothroughrealcodeandstartlearningtoldquopatternmatchrdquothephrasesyoujustlearnedagainsthowtheyrsquoreusedIfyoudrillthisenoughyoushouldstarttoseethesepatternsshoutatyouinthecodewhereasbeforetheyjustseemedlikevagueblankspotsyoudidnrsquotknow

CommonStudentQuestionsWhatdoesresult=sentence[]doThatrsquosaPythonwayofcopyingalistYoursquoreusingthelistslicesyntax[]toeffectivelymakeaslicefromtheveryfirstelementtotheverylastone

ThisscriptishardtogetrunningBythispointyoushouldbeabletotypethisinandgetitworkingItdoeshaveafewlittletrickshereandtherebuttherersquosnothingcomplexaboutitJustdoallthethingsyoursquovelearnedsofartodebugscriptsTypeeachlineinconfirmthatitrsquosexactlylikemineandresearchanythingyoudonrsquotknowonline

ItrsquosstilltoohardYoucandothisTakeitveryslowcharacterbycharacterifyouhavetobuttypeitinexactlyandfigureoutwhatitdoes

Exercise42Is-AHas-AObjectsandClasses

AnimportantconceptthatyouhavetounderstandisthedifferencebetweenaclassandanobjectTheproblemisthereisnorealldquodifferencerdquobetweenaclassandanobjectTheyareactuallythesamethingatdifferentpointsintimeIwilldemonstratewithaZenkoanWhatisthedifferencebetweenafishandasalmonDidthatquestionsortofconfuseyouReallysitdownandthinkaboutitforaminuteImeanafishandasalmonaredifferentbutwaittheyarethesamethingrightAsalmonisakindoffishsoImeanitrsquosnotdifferentButatthesametimeasalmonisaparticulartypeoffishsoitrsquosactuallydifferentfromallotherfishThatrsquoswhatmakesitasalmonandnotahalibutSoasalmonandafisharethesamebutdifferentWeirdThisquestionisconfusingbecausemostpeopledonotthinkaboutrealthingsthiswaybuttheyintuitivelyunderstandthemYoudonotneedtothinkaboutthedifferencebetweenafishandasalmonbecauseyouknowhowtheyarerelatedYouknowasalmonisakindoffishandthatthereareotherkindsoffishwithouthavingtounderstandthatLetrsquostakeitonestepfurtherLetrsquossayyouhaveabucketfullofthreesalmonandbecauseyouareanicepersonyouhavedecidedtonamethemFrankJoeandMaryNowthinkaboutthisquestionWhatisthedifferencebetweenMaryandasalmonAgainthisisaweirdquestionbutitrsquosabiteasierthanthefishversussalmonquestionYouknowthatMaryisasalmonsoshersquosnotreallydifferentShersquosjustaspecificldquoinstancerdquoofasalmonJoeandFrankarealsoinstancesofsalmonWhatdoImeanwhenIsayinstanceImeantheywerecreatedfromsomeothersalmonandnowrepresentarealthingthathassalmon-likeattributesNowforthemind-bendingideaFishisaclassandSalmonisaclassandMaryisanobjectThinkaboutthatforasecondLetrsquosbreakitdownslowlyandseeifyougetitAfishisaclassmeaningitrsquosnotarealthingbutratherawordweattachtoinstancesofthingswithsimilarattributesGotfinsGotgillsLivesinwaterAlrightitrsquosprobablyafishSomeonewithaPhDthencomesalongandsaysldquoNomyyoungfriendthisfishisactuallySalmosalaraffectionatelyknownasasalmonrdquoThisprofessorhasjustclarifiedthefishfurtherandmadeanewclasscalledldquoSalmonrdquothathas

morespecificattributesLongernosereddishfleshbiglivesintheoceanorfreshwatertastyProbablyasalmonFinallyacookcomesalongandtellsthePhDldquoNoyouseethisSalmonrighthereIrsquollcallherMaryandIrsquomgoingtomakeatastyfilletoutofherwithanicesaucerdquoNowyouhavethisinstanceofasalmon(whichalsoisaninstanceofafish)namedMaryturnedintosomethingrealthatisfillingyourbellyIthasbecomeanobjectThereyouhaveitMaryisakindofsalmonthatisakindoffishmdashobjectisaclassisaclass

HowThisLooksinCodeThisisaweirdconceptbuttobeveryhonestyouonlyhavetoworryaboutitwhenyoumakenewclassesandwhenyouuseaclassIwillshowyoutwotrickstohelpyoufigureoutwhethersomethingisaclassoranobjectFirstyouneedtolearntwocatchphrasesldquois-ardquoandldquohas-ardquoYouusethephraseis-awhenyoutalkaboutobjectsandclassesbeingrelatedtoeachotherbyaclassrelationshipYouusehas-awhenyoutalkaboutobjectsandclassesthatarerelatedonlybecausetheyreferenceeachotherNowgothroughthispieceofcodeandreplaceeachcommentwithacommentthatsayswhetherthenextlinerepresentsanis-aorahas-arelationshipandwhatthatrelationshipisInthebeginningofthecodeIrsquovelaidoutafewexamplessoyoujusthavetowritetheremainingonesRememberis-aistherelationshipbetweenfishandsalmonwhilehas-aistherelationshipbetweensalmonandgillsClickheretoviewcodeimage

ex42py

1Animalis-aobject(yessortofconfusing)lookatthe

extracredit

2classAnimal(object)

3pass

4

5

6classDog(Animal)

7

8def__init__(selfname)

9

10selfname=name

11

12

13classCat(Animal)

14

15def__init__(selfname)

16

17selfname=name

18

19

20classPerson(object)

21

22def__init__(selfname)

23

24selfname=name

25

26Personhas-apetofsomekind

27selfpet=None

28

29

30classEmployee(Person)

31

32def__init__(selfnamesalary)

33hmmwhatisthisstrangemagic

34super(Employeeself)__init__(name)

35

36selfsalary=salary

37

38

39classFish(object)

40pass

41

42

43classSalmon(Fish)

44pass

45

46

47classHalibut(Fish)

48pass

49

50

51roveris-aDog

52rover=Dog(Rover)

53

54

55satan=Cat(Satan)

56

57

58mary=Person(Mary)

59

60

61marypet=satan

62

63

64frank=Employee(Frank120000)

65

66

67frankpet=rover

68

69

70flipper=Fish()

71

72

73crouse=Salmon()

74

75

76harry=Halibut()

AboutclassName(object)InPython3youdonotneedtoaddthe(object)afterthenameoftheclassbutthePythoncommunitybelievesinldquoexplicitisbetterthanimplicitrdquosoIandotherPythonexpertshavedecidedtoincludeitYoumayrunintocodethatdoesnothave(object)aftersimpleclassesandthoseclassesareperfectlyfineandwillworkwithclassesyoucreatethatdohave(object)AtthispointitissimplyextradocumentationandhasnoimpactonhowyourclassesworkInPython2therewasadifferencebetweenthetwotypesofclassesbutnowyoudonrsquothavetoworryaboutitTheonlytrickyparttousing(object)involvesthementalgymnasticsofsayingldquoclassNameisaclassoftypeobjectrdquoThatmaysoundconfusingtoyounowsinceitrsquosaclassthatrsquosanameobjectthatrsquosaclassbutdonrsquotfeelbadaboutthatJustthinkofclassName(object)assayingldquothisisabasicsimpleclassrdquoandyoursquollbefineFinallyinthefuturethestylesandtastesofPythonprogrammersmaychangeandthisexplicituseof(object)mightbeseenasasignthatyouareabadprogrammerIfthathappenssimplystopusingitortellthemldquoPythonZensaysexplicitisbetterthanimplicitrdquo

StudyDrills1ResearchwhyPythonaddedthisstrangeobjectclassandwhatthatmeans2Isitpossibletouseaclasslikeitrsquosanobject3FillouttheanimalsfishandpeopleinthisexercisewithfunctionsthatmakethemdothingsSeewhathappenswhenfunctionsareinaldquobase

classrdquolikeAnimalversusinsayDog4Findotherpeoplersquoscodeandworkoutalltheis-aandhas-arelationships5Makesomenewrelationshipsthatarelistsanddictionariessoyoucanalsohaveldquohas-manyrdquorelationships

6Doyouthinktherersquossuchthingasanldquois-manyrdquorelationshipReadaboutldquomultipleinheritancerdquothenavoiditifyoucan

CommonStudentQuestionsWhatarethesecommentsforThoseareldquofill-in-the-blankrdquocommentsthatyouaresupposedtofillinwiththerightis-aandhas-aconceptsReadthisexerciseagainandlookattheothercommentstoseewhatImean

Whatisthepointofselfpet=NoneThatmakessurethattheselfpetattributeofthatclassissettoadefaultofNone

Whatdoessuper(Employeeself)__init__(name)doThatrsquoshowyoucanrunthe__init__methodofaparentclassreliablySearchforldquopython36superrdquoandreadthevariousadviceonitbeingevilandgoodforyou

Exercise43BasicObject-OrientedAnalysisandDesign

IrsquomgoingtodescribeaprocesstousewhenyouwanttobuildsomethingusingPythonspecificallywithobject-orientedprogramming(OOP)WhatImeanbyaldquoprocessrdquoisthatIrsquollgiveyouasetofstepsthatyoudoinorderbutthatyouarenrsquotmeanttobeaslavetoandthatmightnotalwaysworkforeveryproblemTheyarejustagoodstartingpointformanyprogrammingproblemsandshouldnrsquotbeconsideredtheonlywaytosolvethesetypesofproblemsThisprocessisjustonewaytodoitthatyoucanfollowTheprocessisasfollows1Writeordrawabouttheproblem

2Extractkeyconceptsfrom1andresearchthem3Createaclasshierarchyandobjectmapfortheconcepts4Codetheclassesandatesttorunthem5Repeatandrefine

ThewaytolookatthisprocessisthatitisldquotopdownrdquomeaningitstartsfromtheveryabstractlooseideaandthenslowlyrefinesituntiltheideaissolidandsomethingyoucancodeIstartbyjustwritingabouttheproblemandtryingtothinkupanythingIcanaboutitMaybeIrsquollevendrawadiagramortwomaybeamapofsomekindorevenwritemyselfaseriesofemailsdescribingtheproblemThisgivesmeawaytoexpressthekeyconceptsintheproblemandalsoexplorewhatImightalreadyknowaboutitThenIgothroughthesenotesdrawingsanddescriptionsandIpulloutthekeyconceptsTherersquosasimpletricktodoingthisImakealistofallthenounsandverbsinmywritinganddrawingsthenwriteouthowtheyrsquorerelatedThisgivesmeagoodlistofnamesforclassesobjectsandfunctionsinthenextstepItakethislistofconceptsandthenresearchanythatIdonrsquotunderstandsoIcanrefinethemfurtherifneededOnceIhavemylistofconceptsIcreateasimpleoutlinetreeoftheconceptsandhowtheyarerelatedasclassesIcanusuallytakemylistofnounsandstartaskingldquoIsthisonelikeotherconceptnounsThatmeanstheyhaveacommonparentclasssowhatisitcalledrdquoIkeepdoingthisuntilIhaveaclasshierarchythatrsquosjustasimpletreelistoradiagramThenItaketheverbsIhaveandseeifthosearefunctionnamesforeachclassandputtheminmytree

WiththisclasshierarchyfiguredoutIsitdownandwritesomebasicskeletoncodethathasjusttheclassestheirfunctionsandnothingmoreIthenwriteatestthatrunsthiscodeandmakessuretheclassesIrsquovemademakesenseandworkrightSometimesImaywritethetestfirstandothertimesImightwritealittletestalittlecodealittletestandsoonuntilIhavethewholethingbuiltFinallyIkeepcyclingoverthisprocessrepeatingitandrefiningasIgoandmakingitasclearasIcanbeforedoingmoreimplementationIfIgetstuckatanyparticularpartbecauseofaconceptorproblemIhavenrsquotanticipatedthenIsitdownandstarttheprocessoveronjustthatparttofigureitoutmorebeforecontinuingIwillnowgothroughthisprocesswhilecomingupwithagameengineandagameforthisexercise

TheAnalysisofaSimpleGameEngineThegameIwanttomakeiscalledldquoGothonsfromPlanetPercal25rdquoanditwillbeasmallspaceadventuregameWithnothingmorethanthatconceptinmymindIcanexploretheideaandfigureouthowtomakethegamecometolife

WriteorDrawAbouttheProblemIrsquomgoingtowritealittleparagraphforthegameldquoAlienshaveinvadedaspaceshipandourherohastogothroughamazeofroomsdefeatingthemsohecanescapeintoanescapepodtotheplanetbelowThegamewillbemorelikeaZorkorAdventuretypegamewithtextoutputsandfunnywaystodieThegamewillinvolveanenginethatrunsamapfullofroomsorscenesEachroomwillprintitsowndescriptionwhentheplayerentersitandthentelltheenginewhatroomtorunnextoutofthemaprdquoAtthispointIhaveagoodideaforthegameandhowitwouldrunsonowIwanttodescribeeachsceneDeathThisiswhentheplayerdiesandshouldbesomethingfunny

CentralCorridorThisisthestartingpointandhasaGothonalreadystandingtherethattheplayershavetodefeatwithajokebeforecontinuing

LaserWeaponArmoryThisiswheretheherogetsaneutronbombtoblowuptheshipbeforegettingtotheescapepodIthasakeypadtheherohastoguessthenumberfor

TheBridgeThisisanotherbattlescenewithaGothonwheretheheroplacesthebomb

EscapePodThisiswheretheheroescapesbutonlyafterguessingtherightescapepod

AtthispointImightdrawoutamapofthesemaybewritemoredescriptionsofeachroommdashwhatevercomestomindasIexploretheproblem

ExtractKeyConceptsandResearchThemInowhaveenoughinformationtoextractsomeofthenounsandanalyzetheirclasshierarchyFirstImakealistofallthenouns

bullAlienbullPlayerbullShipbullMazebullRoombullScenebullGothonbullEscapePodbullPlanetbullMapbullEnginebullDeathbullCentralCorridorbullLaserWeaponArmorybullTheBridge

IwouldalsopossiblygothroughalltheverbsandseeifanyofthemmightbegoodfunctionnamesbutIrsquollskipthatfornowAtthispointImightalsoresearcheachoftheseconceptsandanythingIdonrsquotknowrightnowForexampleImightplayafewofthesetypesofgamesandmakesureIknowhowtheyworkImightresearchhowshipsaredesignedorhowbombsworkMaybeIrsquollresearchsometechnicalissuelikehowtostorethegamersquosstateinadatabaseAfterIrsquovedonethisresearchImightstartoveratstep1basedonnewinformationIhaveandrewritemydescriptionandextractnewconcepts

CreateaClassHierarchyandObjectMapfortheConceptsOnceIhavethatIturnitintoaclasshierarchybyaskingldquoWhatissimilartootherthingsrdquoIalsoaskldquoWhatisbasicallyjustanotherwordforanotherthingrdquo

RightawayIseethatldquoRoomrdquoandldquoScenerdquoarebasicallythesamethingdependingonhowIwanttodothingsIrsquomgoingtopickldquoScenerdquoforthisgameThenIseethatallthespecificroomslikeldquoCentralCorridorrdquoarebasicallyjustScenesIseealsothatDeathisbasicallyaScenewhichconfirmsmychoiceofldquoScenerdquooverldquoRoomrdquosinceyoucanhaveadeathscenebutadeathroomiskindofoddldquoMazerdquoandldquoMaprdquoarebasicallythesamesoIrsquomgoingtogowithldquoMaprdquosinceIuseditmoreoftenIdonrsquotwanttodoabattlesystemsoIrsquomgoingtoignoreldquoAlienrdquoandldquoPlayerrdquoandsavethatforlaterTheldquoPlanetrdquocouldalsojustbeanothersceneinsteadofsomethingspecificAfterallofthatthoughtprocessIstarttomakeaclasshierarchythatlookslikethisinmytexteditorMapEngineSceneDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodIthengothroughandfigureoutwhatactionsareneededoneachthingbasedonverbsinthedescriptionForexampleIknowfromthedescriptionIrsquomgoingtoneedawaytoldquorunrdquotheengineldquogetthenextscenerdquofromthemapgettheldquoopeningscenerdquoandldquoenterrdquoasceneIrsquolladdthoselikethisMapndashnext_scenendashopening_sceneEnginendashplayScenendashenterDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodNoticehowIjustput-enterunderScenesinceIknowthatallthescenesunderitwillinherititandhavetooverrideitlater

CodetheClassesandaTesttoRunThemOnceIhavethistreeofclassesandsomeofthefunctionsIopenupasourcefileinmyeditorandtrytowritethecodeforitUsuallyIrsquolljustcopy-pastethetreeintothesourcefileandthenedititintoclassesHerersquosasmallexampleofhow

intothesourcefileandthenedititintoclassesHerersquosasmallexampleofhowthismightlookatfirstwithasimplelittletestattheendofthefileClickheretoviewcodeimage

ex43_classespy

1classScene(object)

2

3defenter(self)

4pass

5

6

7classEngine(object)

8

9def__init__(selfscene_map)

10pass

11

12defplay(self)

13pass

14

15classDeath(Scene)

16

17defenter(self)

18pass

19

20classCentralCorridor(Scene)

21

22defenter(self)

23pass

24

25classLaserWeaponArmory(Scene)

26

27defenter(self)

28pass

29

30classTheBridge(Scene)

31

32defenter(self)

33pass

34

35classEscapePod(Scene)

36

37defenter(self)

38pass

39

40

41classMap(object)

42

43def__init__(selfstart_scene)

44pass

45

46defnext_scene(selfscene_name)

47pass

48

49defopening_scene(self)

50pass

51

52

53a_map=Map(central_corridor)

54a_game=Engine(a_map)

55a_gameplay()InthisfileyoucanseethatIsimplyreplicated

thehierarchyIwantedandthenaddedalittlebitofcodeattheend

torunitandseeifitallworksinthisbasicstructureInthe

latersectionsofthisexerciseyoursquollfillintherestofthiscode

andmakeitworktomatchthedescriptionofthegame

RepeatandRefineThelaststepinmylittleprocessisnrsquotsomuchastepasitisawhile-loopYoudonrsquoteverdothisasaone-passoperationInsteadyougobackoverthewholeprocessagainandrefineitbasedoninformationyoursquovelearnedfromlaterstepsSometimesIrsquollgettostep3andrealizethatIneedtoworkon1and2moresoIrsquollstopandgobackandworkonthoseSometimesIrsquollgetaflashofinspirationandjumptotheendtocodeupthesolutioninmyheadwhileIhaveittherebutthenIrsquollgobackanddothepreviousstepstomakesureIcoverallthepossibilitiesIhaveTheotherideainthisprocessisthatitrsquosnotjustsomethingyoudoatonesinglelevelbutsomethingthatyoucandoateverylevelwhenyourunintoaparticularproblemLetrsquossayIdonrsquotknowhowtowritetheEngineplaymethodyetIcanstopanddothiswholeprocessonjustthatonefunctiontofigureouthowtowriteit

TopDownversusBottomUpTheprocessistypicallylabeledldquotopdownrdquosinceitstartsatthemostabstractconcepts(thetop)andworksitswaydowntoactualimplementationIwantyoutousethisprocessIjustdescribedwhenanalyzingproblemsinthebookfromnowonbutyoushouldknowthattherersquosanotherwaytosolveproblemsinprogrammingthatstartswithcodeandgoesldquouprdquototheabstractconceptsThisotherwayislabeledldquobottomuprdquoHerearethegeneralstepsyoufollowtodothis

1Takeasmallpieceoftheproblemhackonsomecodeandgetittorunbarely

barely2Refinethecodeintosomethingmoreformalwithclassesandautomatedtests

3Extractthekeyconceptsyoursquoreusingandresearchthem4Writeadescriptionofwhatrsquosreallygoingon5Gobackandrefinethecodepossiblythrowingitoutandstartingover6Repeatmovingontosomeotherpieceoftheproblem

IfindthisprocessisbetteronceyoursquoremoresolidatprogrammingandarenaturallythinkingincodeaboutproblemsThisprocessisverygoodwhenyouknowsmallpiecesoftheoverallpuzzlebutmaybedonrsquothaveenoughinformationyetabouttheoverallconceptBreakingitdowninlittlepiecesandexploringwithcodethenhelpsyouslowlygrindawayattheproblemuntilyoursquovesolveditHoweverrememberthatyoursolutionwillprobablybemeanderingandweirdsothatrsquoswhymyversionofthisprocessinvolvesgoingbackandfindingresearchthencleaningthingsupbasedonwhatyoursquovelearned

TheCodeforldquoGothonsfromPlanetPercal25rdquoStopIrsquomgoingtoshowyoumyfinalsolutiontotheprecedingproblembutIdonrsquotwantyoutojustjumpinandtypethisupIwantyoutotaketheroughskeletoncodeIdidandtrytomakeitworkbasedonthedescriptionOnceyouhaveyoursolutionthenyoucancomebackandseehowIdiditIrsquomgoingtobreakthisfinalfileex43pydownintosectionsandexplaineachoneratherthandumpallthecodeatonceClickheretoviewcodeimage

ex43py

1fromsysimportexit

2fromrandomimportrandint

3fromtextwrapimportdedentThisisjustourbasicimportsfor

thegameTheonlynewthingistheimportofthededentfunction

fromthetextwrapmoduleThislittlefunctionwillhelpuswriteour

roomdescriptionsusing(triple-quote)stringsItsimplystrips

leadingwhite-spacefromthebeginningsoflinesinastringWithout

thisfunctionusingstylestringsfailsbecausetheyare

indentedonthescreenthesamelevelasinthePythoncode

Clickheretoviewcodeimage

ex43py

1classScene(object)

2

3defenter(self)

4print(Thissceneisnotyetconfigured)

5print(Subclassitandimplemententer())

6exit(1)AsyousawintheskeletoncodeIhaveabase

classforScenethatwillhavethecommonthingsthatallscenesdo

Inthissimpleprogramtheydonrsquotdomuchsothisismorea

demonstrationofwhatyouwoulddotomakeabaseclass

Clickheretoviewcodeimage

ex43py

1classEngine(object)

2

3def__init__(selfscene_map)

4selfscene_map=scene_map

5

6defplay(self)

7current_scene=selfscene_mapopening_scene()

8last_scene=selfscene_mapnext_scene(finished)

9

10whilecurrent_scene=last_scene

11next_scene_name=current_sceneenter()

12current_scene=

selfscene_mapnext_scene(next_scene_name)

13

14besuretoprintoutthelastscene

15current_sceneenter()IalsohavemyEngineclassand

youcanseehowIrsquomalreadyusingthemethodsforMapopening_scene

andMapnext_sceneBecauseIrsquovedoneabitofplanningIcanjust

assumeIrsquollwritethoseandthenusethembeforeIrsquovewrittentheMap

class

Clickheretoviewcodeimage

ex43py

1classDeath(Scene)

2

3quips=[

4YoudiedYoukindasuckatthis

5YourMomwouldbeproudifsheweresmarter

6Suchaluser

7Ihaveasmallpuppythatsbetteratthis

8YoureworsethanyourDadsjokes

9

10]

11

12defenter(self)

13print(Deathquips[randint(0len(selfquips)-1)])

14exit(1)MyfirstsceneistheoddscenenamedDeath

whichshowsyouthesimplestkindofsceneyoucanwrite

Clickheretoviewcodeimage

ex43py

1classCentralCorridor(Scene)

2

3defenter(self)

4print(dedent(

5TheGothonsofPlanetPercal25haveinvadedyour

shipand

6destroyedyourentirecrewYouarethelast

surviving

7memberandyourlastmissionistogettheneutron

destruct

8bombfromtheWeaponsArmoryputitinthebridge

and

9blowtheshipupaftergettingintoanescapepod

10

11Yourerunningdownthecentralcorridortothe

Weapons

12ArmorywhenaGothonjumpsoutredscalyskin

darkgrimy

13teethandevilclowncostumeflowingaroundhis

hate

14filledbodyHesblockingthedoortotheArmory

and

15abouttopullaweapontoblastyou

16))

17

18action=input(gt)

19

20ifaction==shoot

21print(dedent(

22Quickonthedrawyouyankoutyourblaster

andfire

23itattheGothonHisclowncostumeis

flowingand

24movingaroundhisbodywhichthrowsoffyour

aim

25Yourlaserhitshiscostumebutmisseshim

entirely

26Thiscompletelyruinshisbrandnewcostume

hismother

27boughthimwhichmakeshimflyintoan

insanerage

28andblastyourepeatedlyinthefaceuntil

youare

29deadThenheeatsyou

30))

31returndeath

32

33elifaction==dodge

34print(dedent(

35Likeaworldclassboxeryoudodgeweave

slipand

36sliderightastheGothonsblastercranksa

laser

37pastyourheadInthemiddleofyourartful

dodge

38yourfootslipsandyoubangyourheadonthe

metal

39wallandpassoutYouwakeupshortlyafter

onlyto

40dieastheGothonstompsonyourheadand

eatsyou

41))

42returndeath

43

44elifaction==tellajoke

45print(dedent(

46LuckyforyoutheymadeyoulearnGothon

insultsin

47theacademyYoutelltheoneGothonjoke

youknow

48Lbhezbgurevffbsngjurafurfvgfnebhaq

gurubhfr

49furfvgfnebhaqgurubhfrTheGothonstops

tries

50nottolaughthenbustsoutlaughingand

cantmove

51Whileheslaughingyourunupandshoothim

squarein

52theheadputtinghimdownthenjumpthrough

the

53WeaponArmorydoor

54))

55returnlaser_weapon_armory

56

57else

58print(DOESNOTCOMPUTE)

59returncentral_corridor

AfterthatIrsquovecreatedtheCentralCorridorwhichisthestartofthegameIrsquomdoingthescenesforthegamebeforetheMapbecauseIneedtoreferencethemlaterYoushouldalsoseehowIusethededentfunctiononline4TryremovingitlatertoseewhatitdoesClickheretoviewcodeimage

ex43py

1classLaserWeaponArmory(Scene)

2

3defenter(self)

4print(dedent(

5YoudoadiverollintotheWeaponArmory

crouchandscan

6theroomformoreGothonsthatmightbe

hidingItsdead

7quiettooquietYoustandupandruntothe

farsideof

8theroomandfindtheneutronbombinits

container

9Theresakeypadlockontheboxandyouneed

thecodeto

10getthebomboutIfyougetthecodewrong10

timesthen

11thelockclosesforeverandyoucantgetthe

bombThe

12codeis3digits

13))

14

15code=frandint(19)randint(19)randint(19)

16guess=input([keypad]gt)

17guesses=0

18

19whileguess=codeandguesseslt10

20print(BZZZZEDDD)

21guesses+=1

22guess=input([keypad]gt)

23

24ifguess==code

25print(dedent(

26Thecontainerclicksopenandtheseal

breaksletting

27gasoutYougrabtheneutronbombandrun

asfastas

28youcantothebridgewhereyoumustplace

itinthe

29rightspot

30))

31returnthe_bridge

32else

33print(dedent(

34Thelockbuzzesonelasttimeandthenyou

heara

35sickeningmeltingsoundasthemechanismis

fused

36togetherYoudecidetositthereand

finallythe

37Gothonsblowuptheshipfromtheirshipand

youdie

38))

39returndeath

40

41

42

43classTheBridge(Scene)

44

45defenter(self)

46print(dedent(

47YouburstontotheBridgewiththenetron

destructbomb

48underyourarmandsurprise5Gothonswhoare

tryingto

49takecontroloftheshipEachofthemhasan

evenuglier

50clowncostumethanthelastTheyhavent

pulledtheir

51weaponsoutyetastheyseetheactivebomb

underyour

52armanddontwanttosetitoff

53))

54

55action=input(gt)

56

57ifaction==throwthebomb

58print(dedent(

59Inapanicyouthrowthebombatthegroup

ofGothons

60andmakealeapforthedoorRightasyou

dropita

61Gothonshootsyourightinthebackkilling

youAs

62youdieyouseeanotherGothonfrantically

tryto

63disarmthebombYoudieknowingtheywill

probably

64blowupwhenitgoesoff

65))

66returndeath

67

68elifaction==slowlyplacethebomb

69print(dedent(

70Youpointyourblasteratthebombunder

yourarmand

71theGothonsputtheirhandsupandstartto

sweat

72Youinchbackwardtothedooropenitand

then

73carefullyplacethebombonthefloor

pointingyour

74blasteratitYouthenjumpbackthrough

thedoor

75punchtheclosebuttonandblastthelockso

the

76GothonscantgetoutNowthatthebombis

placed

77youruntotheescapepodtogetoffthis

tincan

78))

79

80returnescape_pod

81else

82print(DOESNOTCOMPUTE)

83returnthe_bridge

84

85

86classEscapePod(Scene)

87

88defenter(self)

89print(dedent(

90Yourushthroughtheshipdesperatelytryingto

makeitto

91theescapepodbeforethewholeship

explodesItseems

92likehardlyanyGothonsareontheshipsoyour

runis

93clearofinterferenceYougettothechamber

withthe

94escapepodsandnowneedtopickoneto

takeSomeof

95themcouldbedamagedbutyoudonthavetimeto

look

96Theres5podswhichonedoyoutake

97))

98

99good_pod=randint(15)

100guess=input([pod]gt)

101

102

103ifint(guess)=good_pod

104print(dedent(

105Youjumpintopodguessandhittheeject

button

106Thepodescapesoutintothevoidofspace

then

107implodesasthehullrupturescrushingyour

bodyinto

108jamjelly

109))

110returndeath

111else

112print(dedent(

113Youjumpintopodguessandhittheeject

button

114Thepodeasilyslidesoutintospaceheading

tothe

115planetbelowAsitfliestotheplanet

youlook

116backandseeyourshipimplodethenexplode

likea

117brightstartakingouttheGothonshipat

thesame

118timeYouwon

119))

120

121returnfinished

122

123classFinished(Scene)

124

125defenter(self)

126print(YouwonGoodjob)

127returnfinished

ThisistherestofthegamersquosscenesandsinceIknowIneedthemandhavethoughtabouthowtheyrsquollflowtogetherIrsquomabletocodethemupdirectlyIncidentallyIwouldnrsquotjusttypeallthiscodeinRememberIsaidtotryandbuildthisincrementallyonelittlebitatatimeIrsquomjustshowingyouthefinalresultClickheretoviewcodeimage

ex43py

1classMap(object)

2

3scenes=

4central_corridorCentralCorridor()

5laser_weapon_armoryLaserWeaponArmory()

6the_bridgeTheBridge()

7escape_podEscapePod()

8deathDeath()

9finishedFinished()

10

11

12def__init__(selfstart_scene)

13selfstart_scene=start_scene

14

15defnext_scene(selfscene_name)

16val=Mapscenesget(scene_name)

17returnval

18

19defopening_scene(self)

20returnselfnext_scene(selfstart_scene)AfterthatI

havemyMapclassandyoucanseeitisstoringeachscenebyname

inadictionaryandthenIrefertothatdictwithMapscenesThis

isalsowhythemapcomesafterthescenesbecausethedictionaryhas

torefertothescenessotheyhavetoexist

Clickheretoviewcodeimage

ex43py

1a_map=Map(central_corridor)

2a_game=Engine(a_map)

3a_gameplay()FinallyIrsquovegotmycodethatrunsthegameby

makingaMapthenhandingthatmaptoanEnginebeforecallingplay

tomakethegamework

WhatYouShouldSeeMakesureyouunderstandthegameandthatyoutriedtosolveityourselffirstOnethingtodoifyoursquorestumpedischeatalittlebyreadingmycodethencontinuetryingtosolveityourselfWhenIrunmygameitlookslikethisClickheretoviewcodeimage

Exercise43Session

$python36ex43py

TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyedyourentirecrewYouarethelastsurviving

memberandyourlastmissionistogettheneutrondestruct

bombfromtheWeaponsArmoryputitinthebridgeand

blowtheshipupaftergettingintoanescapepod

YourerunningdownthecentralcorridortotheWeapons

ArmorywhenaGothonjumpsoutredscalyskindarkgrimy

teethandevilclowncostumeflowingaroundhishate

filledbodyHesblockingthedoortotheArmoryand

abouttopullaweapontoblastyou

gtdodge

Likeaworldclassboxeryoudodgeweaveslipand

sliderightastheGothonsblastercranksalaser

pastyourheadInthemiddleofyourartfuldodge

yourfootslipsandyoubangyourheadonthemetal

wallandpassoutYouwakeupshortlyafteronlyto

dieastheGothonstompsonyourheadandeatsyou

YoureworsethanyourDadsjokes

StudyDrills1ChangeitMaybeyouhatethisgameItcouldbetooviolentormaybeyouarenrsquotintosci-fiGetthegameworkingthenchangeittowhatyoulikeThisisyourcomputeryoumakeitdowhatyouwant

2IhaveabuginthiscodeWhyisthedoorlockguessing11times3Explainhowreturningthenextroomworks4AddcheatcodestothegamesoyoucangetpastthemoredifficultroomsIcandothiswithtwowordsononeline

5GobacktomydescriptionandanalysisthentrytobuildasmallcombatsystemfortheheroandthevariousGothonsheencounters

6ThisisactuallyasmallversionofsomethingcalledaldquofinitestatemachinerdquoReadaboutthemTheymightnotmakesensebuttryanyway

CommonStudentQuestionsWherecanIfindstoriesformyowngamesYoucanmakethemupjustlikeyouwouldtellastorytoafriendOryoucantakesimplescenesfromabookormovieyoulike

Exercise44InheritanceversusComposition

InthefairytalesaboutheroesdefeatingevilvillainstherersquosalwaysadarkforestofsomekindItcouldbeacaveaforestanotherplanetjustsomeplacethateveryoneknowstheheroshouldnrsquotgoOfcourseshortlyafterthevillainisintroducedyoufindoutyestheherohastogotothatstupidforesttokillthebadguyItseemstheherojustkeepsgettingintosituationsthatrequirehimtoriskhislifeinthisevilforestYourarelyreadfairytalesabouttheheroeswhoaresmartenoughtojustavoidthewholesituationentirelyYouneverhearaherosayldquoWaitaminuteifIleavetomakemyfortunesonthehighseasleavingButtercupbehindIcoulddieandthenshersquodhavetomarrysomeuglyprincenamedHumperdinkHumperdinkIthinkIrsquollstayhereandstartaFarmBoyforRentbusinessrdquoIfhedidthattherersquodbenofireswampdyingreanimationswordfightsgiantsoranykindofstoryreallyBecauseofthistheforestinthesestoriesseemstoexistlikeablackholethatdragstheheroinnomatterwhattheydoInobject-orientedprogramminginheritanceistheevilforestExperiencedprogrammersknowtoavoidthisevilbecausetheyknowthatdeepinsidetheDarkForestInheritanceistheEvilQueenMultipleInheritanceShelikestoeatsoftwareandprogrammerswithhermassivecomplexityteethchewingonthefleshofthefallenButtheforestissopowerfulandsotemptingthatnearlyeveryprogrammerhastogointoitandtrytomakeitoutalivewiththeEvilQueenrsquosheadbeforetheycancallthemselvesrealprogrammersYoujustcanrsquotresisttheInheritanceForestrsquospullsoyougoinAftertheadventureyoulearntojuststayoutofthatstupidforestandbringanarmyifyouareeverforcedtogoinagainThisisbasicallyafunnywaytosaythatIrsquomgoingtoteachyousomethingyoushouldusecarefullycalledinheritanceProgrammerswhoarecurrentlyintheforestbattlingtheQueenwillprobablytellyouthatyouhavetogoinTheysaythisbecausetheyneedyourhelpsincewhattheyrsquovecreatedisprobablytoomuchforthemtohandleButyoushouldalwaysrememberthisMostoftheusesofinheritancecanbesimplifiedorreplacedwithcompositionandmultipleinheritanceshouldbeavoidedatallcosts

WhatIsInheritanceInheritanceisusedtoindicatethatoneclasswillgetmostorallofitsfeaturesfromaparentclassThishappensimplicitlywheneveryouwriteclass

Foo(Bar)whichsaysldquoMakeaclassFoothatinheritsfromBarrdquoWhenyoudothisthelanguagemakesanyactionthatyoudooninstancesofFooalsoworkasiftheyweredonetoaninstanceofBarDoingthisletsyouputcommonfunctionalityintheBarclassthenspecializethatfunctionalityintheFooclassasneededWhenyouaredoingthiskindofspecializationtherearethreewaysthattheparentandchildclassescaninteract1Actionsonthechildimplyanactionontheparent

2Actionsonthechildoverridetheactionontheparent3Actionsonthechildaltertheactionontheparent

Iwillnowdemonstrateeachoftheseinorderandshowyoucodeforthem

ImplicitInheritanceFirstIwillshowyoutheimplicitactionsthathappenwhenyoudefineafunctionintheparentbutnotinthechildClickheretoviewcodeimage

ex44apy

1classParent(object)

2

3defimplicit(self)

4print(PARENTimplicit())

5

6classChild(Parent)

7pass

8

9dad=Parent()

10son=Child()

11

12dadimplicit()

13sonimplicit()TheuseofpassundertheclassChildishow

youtellPythonthatyouwantanemptyblockThiscreatesaclass

namedChildbutsaysthattherersquosnothingnewtodefineinit

InsteaditwillinheritallofitsbehaviorfromParentWhenyourun

thiscodeyougetthefollowingExercise44aSession

$python36ex44apy

PARENTimplicit()

PARENTimplicit()NoticehoweventhoughIrsquomcallingsonimplicit()

online13andeventhoughChilddoesnothaveanimplicitfunction

defineditstillworksanditcallstheonedefinedinParentThis

showsyouthatifyouputfunctionsinabaseclass(ieParent)

thenallsubclasses(ieChild)willautomaticallygetthose

featuresVeryhandyforrepetitivecodeyouneedinmanyclasses

OverrideExplicitlyTheproblemwithhavingfunctionscalledimplicitlyissometimesyouwantthechildtobehavedifferentlyInthiscaseyouwanttooverridethefunctioninthechildeffectivelyreplacingthefunctionalityTodothisjustdefineafunctionwiththesamenameinChildHerersquosanexampleClickheretoviewcodeimage

ex44bpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6classChild(Parent)

7

8defoverride(self)

9print(CHILDoverride())

10

11dad=Parent()

12son=Child()

13

14dadoverride()

15sonoverride()InthisexampleIhaveafunctionnamedoverride

inbothclassessoletrsquosseewhathappenswhenIrunit

Exercise44bSession

$python36ex44bpy

PARENToverride()

CHILDoverride()Asyoucanseewhenline14runsitrunsthe

Parentoverridefunctionbecausethatvariable(dad)isaParentBut

whenline15runsitprintsouttheChildoverridemessagesbecause

sonisaninstanceofChildandChildoverridesthatfunctionby

definingitsownversion

Takeabreakrightnowandtryplayingwiththesetwoconceptsbeforecontinuing

AlterBeforeorAfter

AlterBeforeorAfterThethirdwaytouseinheritanceisaspecialcaseofoverridingwhereyouwanttoalterthebehaviorbeforeoraftertheParentclassrsquosversionrunsYoufirstoverridethefunctionjustlikeinthelastexamplebutthenyouuseaPythonbuilt-infunctionnamedsupertogettheParentversiontocallHerersquostheexampleofdoingthatsoyoucanmakesenseofthisdescriptionClickheretoviewcodeimage

ex44cpy

1classParent(object)

2

3defaltered(self)

4print(PARENTaltered())

5

6classChild(Parent)

7

8defaltered(self)

9print(CHILDBEFOREPARENTaltered())

10super(Childself)altered()

11print(CHILDAFTERPARENTaltered())

12

13dad=Parent()

14son=Child()

15

16dadaltered()

17sonaltered()Theimportantlineshereare9ndash11whereinthe

ChildIdothefollowingwhensonaltered()iscalled1Because

IrsquoveoverriddenParentalteredtheChildalteredversionrunsand

line9executeslikeyoursquodexpect

2InthiscaseIwanttodoabeforeandaftersoafterline9IwanttousesupertogettheParentalteredversion

3Online10Icallsuper(Childself)altered()whichisawareofinheritanceandwillgettheParentclassforyouYoushouldbeabletoreadthisasldquocallsuperwithargumentsChildandselfthencallthefunctionalteredonwhateveritreturnsrdquo

4AtthispointtheParentalteredversionofthefunctionrunsandthatprintsouttheParentmessage

5FinallythisreturnsfromtheParentalteredandtheChildalteredfunctioncontinuestoprintouttheaftermessage

IfyourunthisyoushouldseethisClickheretoviewcodeimage

Exercise44cSession

$python36ex44cpy

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

AllThreeCombinedTodemonstratealloftheseIhaveafinalversionthatshowseachkindofinteractionfrominheritanceinonefileClickheretoviewcodeimage

ex44dpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6defimplicit(self)

7print(PARENTimplicit())

8

9defaltered(self)

10print(PARENTaltered())

11

12classChild(Parent)

13

14defoverride(self)

15print(CHILDoverride())

16

17defaltered(self)

18print(CHILDBEFOREPARENTaltered())

19super(Childself)altered()

20print(CHILDAFTERPARENTaltered())

21

22dad=Parent()

23son=Child()

24

25dadimplicit()

26sonimplicit()

27

28dadoverride()

29sonoverride()

30

31dadaltered()

32sonaltered()Gothrougheachlineofthiscodeandwritea

commentexplainingwhatthatlinedoesandwhetheritrsquosanoverride

ornotThenrunitandconfirmyougetwhatyouexpectedClickhere

toviewcodeimage

Exercise44dSession

$python36ex44dpy

PARENTimplicit()

PARENTimplicit()

PARENToverride()

CHILDoverride()

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

TheReasonforsuper()ThisshouldseemlikecommonsensebutthenwegetintotroublewithathingcalledmultipleinheritanceMultipleinheritanceiswhenyoudefineaclassthatinheritsfromoneormoreclasseslikethisClickheretoviewcodeimage

classSuperFun(ChildBadStuff)

passThisislikesayingldquoMakeaclassnamedSuperFunthat

inheritsfromtheclassesChildandBadStuffatthesametimerdquo

InthiscasewheneveryouhaveimplicitactionsonanySuperFuninstancePythonhastolookupthepossiblefunctionintheclasshierarchyforbothChildandBadStuffbutitneedstodothisinaconsistentorderTodothisPythonusesldquomethodresolutionorderrdquo(MRO)andanalgorithmcalledC3togetitstraightBecausetheMROiscomplexandawell-definedalgorithmisusedPythoncanrsquotleaveittoyoutogettheMROrightInsteadPythongivesyouthesuper()functionwhichhandlesallofthisforyouintheplacesthatyouneedthealteringtypeofactionsasIdidinChildalteredWithsuper()youdonrsquothavetoworryaboutgettingthisrightandPythonwillfindtherightfunctionforyou

Usingsuper()with__init__Themostcommonuseofsuper()isactuallyin__init__functionsinbaseclassesThisisusuallytheonlyplacewhereyouneedtodosomethingsina

childthencompletetheinitializationintheparentHerersquosaquickexampleofdoingthatintheChildClickheretoviewcodeimage

classChild(Parent)

def__init__(selfstuff)

selfstuff=stuff

super(Childself)__init__()Thisisprettymuchthesameas

theChildalteredexampleaboveexceptIrsquomsettingsomevariablesin

the__init__beforehavingtheParentinitializewithits

Parent__init__

CompositionInheritanceisusefulbutanotherwaytodotheexactsamethingisjusttouseotherclassesandmodulesratherthanrelyonimplicitinheritanceIfyoulookatthethreewaystoexploitinheritancetwoofthethreeinvolvewritingnewcodetoreplaceoralterfunctionalityThiscaneasilybereplicatedbyjustcallingfunctionsinamoduleHerersquosanexampleofdoingthisClickheretoviewcodeimage

ex44epy

1classOther(object)

2

3defoverride(self)

4print(OTHERoverride())

5

6defimplicit(self)

7print(OTHERimplicit())

8

9defaltered(self)

10print(OTHERaltered())

11

12classChild(object)

13

14def__init__(self)

15selfother=Other()

16

17defimplicit(self)

18selfotherimplicit()

19

20defoverride(self)

21print(CHILDoverride())

22

23defaltered(self)

24print(CHILDBEFOREOTHERaltered())

25selfotheraltered()

26print(CHILDAFTEROTHERaltered())

27

28son=Child()

29

30sonimplicit()

31sonoverride()

32sonaltered()InthiscodeIrsquomnotusingthenameParentsince

thereisnotaparent-childis-arelationshipThisisahas-a

relationshipwhereChildhas-aOtherthatitusestogetitswork

doneWhenIrunthisIgetthefollowingoutputExercise44e

Session

$python36ex44epy

OTHERimplicit()

CHILDoverride()

CHILDBEFOREOTHERaltered()

OTHERaltered()

CHILDAFTEROTHERaltered()Youcanseethatmostofthecodein

ChildandOtheristhesametoaccomplishthesamethingTheonly

differenceisthatIhadtodefineaChildimplicitfunctiontodo

thatoneactionIcouldthenaskmyselfifIneedthisOthertobea

classandcouldIjustmakeitintoamodulenamedotherpy

WhentoUseInheritanceorCompositionThequestionofldquoinheritanceversuscompositionrdquocomesdowntoanattempttosolvetheproblemofreusablecodeYoudonrsquotwanttohaveduplicatedcodealloveryoursoftwaresincethatrsquosnotcleanandefficientInheritancesolvesthisproblembycreatingamechanismforyoutohaveimpliedfeaturesinbaseclassesCompositionsolvesthisbygivingyoumodulesandthecapabilitytocallfunctionsinotherclassesIfbothsolutionssolvetheproblemofreusethenwhichoneisappropriateinwhichsituationsTheanswerisincrediblysubjectivebutIrsquollgiveyoumythreeguidelinesforwhentodowhich1AvoidmultipleinheritanceatallcostsasitrsquostoocomplextobereliableIfyoursquorestuckwithitthenbepreparedtoknowtheclasshierarchyandspendtimefindingwhereeverythingiscomingfrom

2Usecompositiontopackagecodeintomodulesthatareusedinmanydifferentunrelatedplacesandsituations

3Useinheritanceonlywhenthereareclearlyrelatedreusablepiecesofcodethatfitunderasinglecommonconceptorifyouhavetobecauseofsomethingyoursquoreusing

DonotbeaslavetotheserulesThethingtorememberaboutobject-orientedprogrammingisthatitisentirelyasocialconventionprogrammershavecreatedtopackageandsharecodeBecauseitrsquosasocialconventionbutonethatrsquoscodifiedinPythonyoumaybeforcedtoavoidtheserulesbecauseofthepeopleyouworkwithInthatcasefindouthowtheyusethingsandthenjustadapttothesituation

StudyDrillsThereisonlyoneStudyDrillforthisexercisebecauseitisabigexerciseGoandreadhttpwwwpythonorgdevpepspep-0008andstarttryingtouseitinyourcodeYoursquollnoticethatsomeofitisdifferentfromwhatyoursquovebeenlearninginthisbookbutnowyoushouldbeabletounderstandtheirrecommendationsandusetheminyourowncodeTherestofthecodeinthisbookmayormaynotfollowtheseguidelinesdependingonwhetheritmakesthecodemoreconfusingIsuggestyoualsodothisascomprehensionismoreimportantthanimpressingeveryonewithyourknowledgeofesotericstylerules

CommonStudentQuestionsHowdoIgetbetteratsolvingproblemsthatIhavenrsquotseenbeforeTheonlywaytogetbetteratsolvingproblemsistosolveasmanyproblemsasyoucanbyyourselfTypicallypeoplehitadifficultproblemandthenrushouttofindananswerThisisfinewhenyouhavetogetthingsdonebutifyouhavethetimetosolveityourselfthentakethattimeStopandbangyourheadagainsttheproblemforaslongaspossibletryingeverypossiblethinguntilyousolveitorgiveupAfterthattheanswersyoufindwillbemoresatisfyingandyoursquolleventuallygetbetteratsolvingproblems

ArenrsquotobjectsjustcopiesofclassesInsomelanguages(likeJavaScript)thatistrueThesearecalledprototypelanguagesandtherearenotmanydifferencesbetweenobjectsandclassesotherthanusageInPythonhoweverclassesactastemplatesthatldquomintrdquonewobjectssimilartohowcoinsaremintedusingadie(template)

Exercise45YouMakeaGame

YouneedtostartlearningtofeedyourselfHopefullyasyouhaveworkedthroughthisbookyouhavelearnedthatalltheinformationyouneedisontheinternetYoujusthavetogosearchforitTheonlythingyouhavebeenmissingaretherightwordsandwhattolookforwhenyousearchNowyoushouldhaveasenseofitsoitrsquosabouttimeyoustruggledthroughabigprojectandtriedtogetitworkingHereareyourrequirements

1MakeadifferentgamefromtheoneImade2UsemorethanonefileanduseimporttousethemMakesureyouknowwhatthatis

3Useoneclassperroomandgivetheclassesnamesthatfittheirpurposes(likeGoldRoomKoiPondRoom)

4YourrunnerwillneedtoknowabouttheseroomssomakeaclassthatrunsthemandknowsaboutthemTherersquoreplentyofwaystodothisbutconsiderhavingeachroomreturnwhatroomisnextorsettingavariableofwhatroomisnext

OtherthanthatIleaveittoyouSpendawholeweekonthisandmakeitthebestgameyoucanUseclassesfunctionsdictslistsanythingyoucantomakeitniceThepurposeofthislessonistoteachyouhowtostructureclassesthatneedotherclassesinsideotherfilesRememberIrsquomnottellingyouexactlyhowtodothisbecauseyouhavetodothisyourselfGofigureitoutProgrammingisproblemsolvingandthatmeanstryingthingsexperimentingfailingscrappingyourworkandtryingagainWhenyougetstuckaskforhelpandshowpeopleyourcodeIftheyaremeantoyouignorethemandfocusonthepeoplewhoarenotmeanandoffertohelpKeepworkingitandcleaningituntilitrsquosgoodthenshowitsomemoreGoodluckandseeyouinaweekwithyourgame

EvaluatingYourGameInthisexerciseyouwillevaluatethegameyoujustmadeMaybeyougotpartwaythroughitandyougotstuckMaybeyougotitworkingbutjustbarelyEitherwaywersquoregoingtogothroughabunchofthingsyoushouldknownowandmakesureyoucoveredtheminyourgameWersquoregoingtostudyproperlyformattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquo

formattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquoknowledgeWhywouldIhaveyoutrytodoityourselfandthenshowyouhowtodoitrightFromnowoninthebookIrsquomgoingtotrytomakeyouself-sufficientIrsquovebeenholdingyourhandmostlythiswholetimeandIcanrsquotdothatformuchlongerIrsquomnowinsteadgoingtogiveyouthingstodohaveyoudothemonyourownandthengiveyouwaystoimprovewhatyoudidYouwillstruggleatfirstandprobablybeveryfrustratedbutstickwithitandeventuallyyouwillbuildamindforsolvingproblemsYouwillstarttofindcreativesolutionstoproblemsratherthanjustcopysolutionsoutoftextbooks

FunctionStyleAlltheotherrulesIrsquovetaughtyouabouthowtomakeanicefunctionapplyherebutaddthesethings

bullForvariousreasonsprogrammerscallfunctionsthatarepartofclassesldquomethodsrdquoItrsquosmostlymarketingbutjustbewarnedthateverytimeyousayldquofunctionrdquotheyrsquollannoyinglycorrectyouandsayldquomethodrdquoIftheygettooannoyingjustaskthemtodemonstratethemathematicalbasisthatdetermineshowaldquomethodrdquoisdifferentfromaldquofunctionrdquoandtheyrsquollshutup

bullWhenyouworkwithclassesmuchofyourtimeisspenttalkingaboutmakingtheclassldquodothingsrdquoInsteadofnamingafunctionafterwhatthefunctiondoesinsteadnameitasifitrsquosacommandyouaregivingtotheclassForexamplepopissayingldquoHeylistpopthisoffrdquoItisnrsquotcalledremove_from_end_of_listbecauseeventhoughthatrsquoswhatitdoesthatrsquosnotacommandtoalist

bullKeepyourfunctionssmallandsimpleForsomereasonwhenpeoplestartlearningaboutclassestheyforgetthis

ClassStylebullYourclassshoulduseldquocamelcaserdquoasinSuperGoldFactoryratherthanldquounderscoreformatrdquoasinsuper_gold_factory

bullTrynottodotoomuchinyour__init__functionsItmakesthemhardertouse

bullYourotherfunctionsshoulduseunderscoreformatsowritemy_awesome_hairandnotmyawesomehairorMyAwesomeHair

bullBeconsistentinhowyouorganizeyourfunctionargumentsIfyourclass

hastodealwithusersdogsandcatskeepthatorderthroughoutunlessitreallydoesnrsquotmakesenseIfyouhaveonefunctionthattakes(dogcatuser)andtheothertakes(usercatdog)itrsquollbehardtouse

bullTrynottousevariablesthatcomefromthemoduleorglobalsTheyshouldbefairlyself-contained

bullAfoolishconsistencyisthehobgoblinoflittlemindsConsistencyisgoodbutfoolishlyfollowingsomeidioticmantrabecauseeveryoneelsedoesisbadstyleThinkforyourself

bullAlwaysalwayshaveclassName(object)formatorelseyouwillbeinbigtrouble

CodeStylebullGiveyourcodeverticalspacesopeoplecanreaditYouwillfindsomeverybadprogrammerswhoareabletowritereasonablecodebutwhodonotaddanyspacesThisisbadstyleinanylanguagebecausethehumaneyeandbrainusespaceandverticalalignmenttoscanandseparatevisualelementsNothavingspaceisthesameasgivingyourcodeanawesomecamouflagepaintjob

bullIfyoucanrsquotreaditoutlouditrsquosprobablyhardtoreadIfyouarehavingaproblemmakingsomethingeasytousetryreadingitoutloudNotonlydoesthisforceyoutoslowdownandreallyreaditbutitalsohelpsyoufinddifficultpassagesandthingstochangeforreadability

bullTrytodowhatotherpeoplearedoinginPythonuntilyoufindyourownstyle

bullOnceyoufindyourownstyledonotbeajerkaboutitWorkingwithotherpeoplersquoscodeispartofbeingaprogrammerandotherpeoplehavereallybadtasteTrustmeyouwillprobablyhavereallybadtastetooandnotevenrealizeit

bullIfyoufindsomeonewhowritescodeinastyleyouliketrywritingsomethingthatmimicsthatstyle

GoodCommentsbullProgrammerswilltellyouthatyourcodeshouldbereadableenoughthatyoudonotneedcommentsTheyrsquollthentellyouintheirmostofficialsoundingvoiceldquoErgooneshouldneverwritecommentsordocumentationQEDrdquoThoseprogrammersareeitherconsultantswhogetpaidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendto

paidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendtoneverworkwithotherpeopleIgnorethemandwritecomments

bullWhenyouwritecommentsdescribewhyyouaredoingwhatyouaredoingThecodealreadysayshowsowhyyoudidthingsthewayyoudidismoreimportant

bullWhenyouwritedoccommentsforyourfunctionsmakethecommentsdocumentationforsomeonewhowillhavetouseyourcodeYoudonothavetogocrazybutanicelittlesentenceaboutwhatsomeonecandowiththatfunctionhelpsalot

bullWhilecommentsaregoodtoomanyarebadandyouhavetomaintainthemKeepyourcommentsrelativelyshortandtothepointandifyouchangeafunctionreviewthecommenttomakesureitrsquosstillcorrect

EvaluateYourGameIwantyoutonowpretendyouaremeAdoptaverysternlookprintoutyourcodeandtakearedpenandmarkeverymistakeyoufindincludinganythingfromthisexerciseandfromotherguidelinesyoursquovereadsofarOnceyouaredonemarkingyourcodeupIwantyoutofixeverythingyoucameupwithThenrepeatthisacoupleoftimeslookingforanythingthatcouldbebetterUseallthetricksIrsquovegivenyoutobreakyourcodedownintothesmallesttiniestlittleanalysisyoucanThepurposeofthisexerciseistotrainyourattentiontodetailonclassesOnceyouaredonewiththisbitofcodefindsomeoneelsersquoscodeanddothesamethingGothroughaprintedcopyofsomepartofitandpointoutallthemistakesandstyleerrorsyoufindThenfixitandseeifyourfixescanbedonewithoutbreakingthatprogramIwantyoutodonothingbutevaluateandfixcodefortheweekmdashyourowncodeandotherpeoplersquosItrsquollbeprettyhardworkbutwhenyouaredoneyourbrainwillbewiredtightlikeaboxerrsquoshands

Exercise46AProjectSkeleton

ThiswillbewhereyoustartlearninghowtosetupagoodprojectldquoskeletonrdquodirectoryThisskeletondirectorywillhaveallthebasicsyouneedtogetanewprojectupandrunningItwillhaveyourprojectlayoutautomatedtestsmodulesandinstallscriptsWhenyougotomakeanewprojectjustcopythisdirectorytoanewnameandeditthefilestogetstarted

macOSLinuxSetupBeforeyoucanbeginthisexerciseyouneedtoinstallsomesoftwareforPythonbyusingatoolcalledpip36(orjustpip)toinstallnewmodulesThepip36commandshouldbeincludedwithyourpython36installationYoursquollwanttoverifythisusingthiscommand

$pip36list

pip(901)

setuptools(2880)

$

YoucanignoreanydeprecationwarningifyouseeitYoumayalsoseeothertoolsinstalledbutthebaseshouldbepipandsetuptoolsOnceyoursquoveverifiedthisyoucantheninstallvirtualenvClickheretoviewcodeimage

$sudopip36installvirtualenv

Password

Collectingvirtualenv

Downloadingvirtualenvndash1510ndashpy2py3ndashnonendashanywhl(18MB)

100|||||||||||||||||||||||||||||||||18MB11MBs

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

$

ThisisforLinuxormacOSsystemsIfyoursquoreonLinuxmacOSyoursquollwanttorunthefollowingcommandtomakesureyouusethecorrectvirtualenvClickheretoviewcodeimage

$whereisvirtualenv

LibraryFrameworksPythonframeworkVersions36binvirtualenv

YoushouldseesomethingliketheaboveonmacOSbutLinuxwillbevariableOnLinuxyoumighthaveanactualvirtualenv36commandoryoumay

bebetteroffinstallingapackageforitfromyourpackagemanagementsystemOnceyoursquoveinstalledvirtualenvyoucanuseittocreatealdquofakerdquoPythoninstallationwhichmakesiteasiertomanageversionsofyourpackagesfordifferentprojectsFirstrunthiscommandandIrsquollexplainwhatitrsquosdoingClickheretoviewcodeimage

$mkdir~venvs

$virtualenvndashndashsystemndashsitendashpackages~venvslpthw

$~venvslpthwbinactivate

(lpthw)$

Herersquoswhatrsquosgoingonlinebyline1YoucreateadirectorycalledvenvsinyourHOME~tostoreallyourvirtualenvironments

2Yourunvirtualenvandtellittoincludethesystemsitepackages(--system-site-packages)theninstructittobuildthevirtualenvin~venvslpthw

3Youthenldquosourcerdquothelpthwvirtualenvironmentbyusingtheoperatorinbashfollowedbythe~venvslpthwbinactivatescript

4Finallyyourpromptchangestoinclude(lpthw)soyouknowthatyoursquoreusingthatvirtualenvironment

NowyoucanseewherethingsareinstalledClickheretoviewcodeimage

(lpthw)$whichpython

Userszedshawvenvslpthwbinpython

(lpthw)$python

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

(lpthw)$

YoucanseethatthepythonthatgetsrunisinstalledintheUserszedshawvenvslpthwbinpythondirectoryinsteadoftheoriginallocationThisalsosolvestheproblemofhavingtotypepython36sinceitinstallsbothClickheretoviewcodeimage

$whichpython36

Userszedshawvenvslpthwbinpython36

(lpthw)$

YoursquollfindthesamethingforvirtualenvandpipcommandsThefinalstepinthissetupistoinstallnoseatestingframeworkwersquolluseinthisexerciseClickheretoviewcodeimage

$pipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB32MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)$

Windows10SetupTheWindows10installisalittlesimplerthanonLinuxormacOSbutonlyifyouhaveoneversionofPythoninstalledIfyouhavebothPython36andPython27installedthenyouareonyourownasitismuchtoodifficulttomanagemultipleinstallationsIfyouhavefollowedthebooksofarandhaveonlyPython36thenherersquoswhatyoudoFirstchangetoyourhomedirectoryandconfirmyoursquorerunningtherightversionofpythonClickheretoviewcodeimage

gtcd~

gtpython

Python360(v36041df79263a11Dec232016080612)

[MSCv190064bit(AMD64)]onwin32

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

Thenyoursquollwanttorunpiptoconfirmyouhaveabasicinstall

gtpiplist

pip(901)

setuptools(2880)

YoucansafelyignoreanydeprecationwarninganditrsquosalrightifyouhaveotherpackagesinstalledNextyoursquollinstallvirtualenvforsettingupsimplevirtualenvironmentsfortherestofthebookClickheretoviewcodeimage

gtpipinstallvirtualenv

Collectingvirtualenv

Usingcachedvirtualenvndash1510ndashpy2py3ndashnonendashanywhl

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

OnceyouhavevirtualenvinstalledyoursquollneedtomakeavenvsdirectoryandfillitwithavirtualenvironmentClickheretoviewcodeimage

gtmkdirvenvs

gtvirtualenvndashndashsystemndashsitendashpackagesvenvslpthw

Usingbaseprefix

cuserszedshappdatalocalprogramspythonpython36

Newpythonexecutablein

CUserszedshawvenvslpthwScriptspythonexe

Installingsetuptoolspipwheeldone

ThosetwocommandscreateavenvsfolderforstoringdifferentvirtualenvironmentsandthencreateyourfirstonenamedlpthwAvirtualenvironment(virtualenv)isaldquofakerdquoplacetoinstallsoftwaresothatyoucanhavedifferentversionsofdifferentpackagesforeachprojectyoursquoreworkingonOnceyouhavethevirtualenvsetupyouneedtoactivateitClickheretoviewcodeimage

gtvenvslpthwScriptsactivate

ThatwillruntheactivatescriptforPowerShellwhichconfiguresthelpthwvirtualenvforyourcurrentshellEverytimeyouwanttouseyoursoftwareforthebookyoursquollrunthiscommandYoursquollnoticeinournextcommandthatthereisnowa(lpthw)addedtothePowerShellpromptshowingyouwhichvirtualenvyoursquoreusingFinallyyoujustneedtoinstallnoseforrunningtestslaterClickheretoviewcodeimage

(lpthw)gtpipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB12MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)gt

YoursquollseethatthisinstallsnoseexceptpipwillinstallitintoyourvenvslpthwvirtualenvironmentinsteadofthemainsystempackagesdirectoryThisletsyouinstallconflictingversionsofPythonpackagesforeachprojectyouworkonwithoutinfectingyourmainsystemconfiguration

CreatingtheSkeletonProjectDirectoryFirstcreatethestructureofyourskeletondirectorywiththesecommands

$mkdirprojects

$cdprojects

$mkdirskeleton

$cdskeleton

$mkdirbinNAMEtestsdocs

IuseadirectorynamedprojectstostoreallthevariousthingsIrsquomworkingonInsidethatdirectoryIhavemyskeletondirectorythatIputthebasisofmyprojectsintoThedirectoryNAMEwillberenamedtowhateveryouarecallingyourprojectrsquosmainmodulewhenyouusetheskeletonNextweneedtosetupsomeinitialfilesHerersquoshowyoudothatonLinuxmacOS

$touchNAME__init__py

$touchtests__init__py

HerersquosthesamethingonWindowsPowerShellClickheretoviewcodeimage

$newndashitemndashtypefileNAME__init__py

$newndashitemndashtypefiletests__init__py

ThatcreatesanemptyPythonmoduledirectorywecanputourcodeinThenweneedtocreateasetuppyfilewecanusetoinstallourprojectlaterifwewantClickheretoviewcodeimage

setuppy

1try

2fromsetuptoolsimportsetup

3exceptImportError

4fromdistutilscoreimportsetup

5

6config=

7descriptionMyProject

8authorMyName

9urlURLtogetitat

10download_urlWheretodownloadit

11author_emailMyemail

12version01

13install_requires[nose]

14packages[NAME]

15scripts[]

16nameprojectname

17

18

19setup(config)

EditthisfilesothatithasyourcontactinformationandisreadytogoforwhenyoucopyitFinallyyouwillwantasimpleskeletonfilefortestsnamedtestsNAME_testspyClickheretoviewcodeimage

NAME_testspy

1fromnosetoolsimport

2importNAME

3

4defsetup()

5print(SETUP)

6

7defteardown()

8print(TEARDOWN)

9

10deftest_basic()

11print(IRAN)

FinalDirectoryStructureWhenyouaredonesettingallofthisupyourdirectoryshouldlooklikeminehere

skeleton

NAME

__init__py

bin

docs

setuppy

tests

NAME_testspy

__init__py

AndfromnowonyoushouldrunyourcommandsfromthisdirectoryIfyoucanrsquotdols-RandifyoudonrsquotseethissamestructurethenyouareinthewrongplaceForexamplepeoplecommonlygointothetestsdirectoryto

trytorunfilestherewhichwonrsquotworkTorunyourapplicationrsquostestsyouwouldneedtobeabovetestsandthislocationIhaveaboveSoifyoutrythisClickheretoviewcodeimage

$cdtestsWRONGWRONGWRONG

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran0testsin0000s

OK

ThatiswrongYouhavetobeabovetestssoassumingyoumadethismistakeyouwouldfixitbydoingthisClickheretoviewcodeimage

$cdgetoutoftests

$lsCORRECTyouarenowintherightspot

NAMEbindocssetuppytests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0004s

OK

Rememberthisbecausepeoplemakethismistakequitefrequently

WarningAtthetimeofpublicationIlearnedthatthenoseprojecthasbeenabandonedandmightnotworkwellIfyouhavestrangesyntaxerrorswhenyourunnoseteststhenlookattheerroroutputIfitreferencesldquopython27rdquointheoutputthenchancesarenosetestsistryingtorunthe27versionofPythononyourcomputerThesolutionistorunnoseusingpython36-mnoseonLinuxormacOSOnWindowsyoumaynothavethisproblembutusingpython-mnosewillsolveitifyoudo

TestingYourSetupAfteryougetallthatinstalledyoushouldbeabletodothis

$nosetests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0007s

OK

IrsquollexplainwhatthisnoseteststhingisdoinginthenextexercisebutfornowifyoudonotseethatyouprobablygotsomethingwrongMakesureyouput__init__pyfilesinyourNAMEandtestsdirectoriesandmakesureyougottestsNAME_testspyright

UsingtheSkeletonYouarenowdonewithmostofyouryakshavingWheneveryouwanttostartanewprojectjustdothis

1MakeacopyofyourskeletondirectoryNameitafteryournewproject2Rename(move)theNAMEdirectorytobethenameofyourprojectorwhateveryouwanttocallyourrootmodule

3Edityoursetuppytohavealltheinformationforyourproject4RenametestsNAME_testspytoalsohaveyourmodulename5Doublecheckitrsquosallworkingbyusingnosetestsagain6Startcoding

RequiredQuizThisexercisedoesnrsquothaveStudyDrillsinsteadherersquosquizyoushouldcomplete

1Readabouthowtouseallofthethingsyouinstalled2ReadaboutthesetuppyfileandallithastoofferWarningItisnotaverywell-writtenpieceofsoftwaresoitwillbeverystrangetouse

3Makeaprojectandstartputtingcodeintothemodulethengetthemoduleworking

4PutascriptinthebindirectorythatyoucanrunReadabouthowyoucanmakeaPythonscriptthatrsquosrunnableforyoursystem

5Mentionthebinscriptyoucreatedinyoursetuppysothatitgetsinstalled

6Useyoursetuppytoinstallyourownmoduleandmakesureitworksthenusepiptouninstallit

CommonStudentQuestions

CommonStudentQuestionsDotheseinstructionsworkonWindowsTheyshouldbutdependingontheversionofWindowsyoumayneedtostrugglewiththesetupabittogetitworkingJustkeepresearchingandtryingituntilyougetitorseeifyoucanaskamoreexperiencedPython+Windowsfriendtohelpout

WhatdoIputintheconfigdictionaryinmysetuppyMakesureyoureadthedocumentationfordistutilsathttpdocspythonorgdistutilssetupscripthtml

IcanrsquotseemtoloadtheNAMEmoduleandjustgetanImportErrorMakesurethatyoumadetheNAME__init__pyfileIfyoursquoreonWindowsmakesureyoudidnrsquotaccidentallynameitNAME__init__pytxtwhichhappensbydefaultwithsomeeditors

WhydoweneedabinfolderatallThisisjustastandardplacetoputscriptsthatarerunonthecommandlinenotaplacetoputmodules

MynosetestsrunonlyshowsonetestbeingrunIsthatrightYesthatrsquoswhatmyoutputshowstoo

Exercise47AutomatedTesting

HavingtotypecommandsintoyourgameoverandovertomakesureitrsquosworkingisannoyingWouldnrsquotitbebettertowritelittlepiecesofcodethattestyourcodeThenwhenyoumakeachangeoraddanewthingtoyourprogramyoujustldquorunyourtestsrdquoandthetestsmakesurethingsarestillworkingTheseautomatedtestswonrsquotcatchallyourbugsbuttheywillcutdownonthetimeyouspendrepeatedlytypingandrunningyourcodeEveryexerciseafterthisonewillnothaveaWhatYouShouldSeesectionbutinsteadwillhaveaWhatYouShouldTestsectionYouwillbewritingautomatedtestsforallofyourcodestartingnowandthiswillhopefullymakeyouanevenbetterprogrammerIwonrsquottrytoexplainwhyyoushouldwriteautomatedtestsIwillonlysaythatyouaretryingtobeaprogrammerandprogrammersautomateboringandtedioustasksTestingapieceofsoftwareisdefinitelyboringandtedioussoyoumightaswellwritealittlebitofcodetodoitforyouThatshouldbealltheexplanationyouneedbecauseyourreasonforwritingunittestsistomakeyourbrainstrongerYouhavegonethroughthisbookwritingcodetodothingsNowyouaregoingtotakethenextleapandwritecodethatknowsaboutothercodeyouhavewrittenThisprocessofwritingatestthatrunssomecodeyouhavewrittenforcesyoutounderstandclearlywhatyouhavejustwrittenItsolidifiesinyourbrainexactlywhatitdoesandwhyitworksandgivesyouanewlevelofattentiontodetail

WritingaTestCaseWersquoregoingtotakeaverysimplepieceofcodeandwriteonesimpletestWersquoregoingtobasethislittletestonanewprojectfromyourprojectskeletonFirstmakeanex47projectfromyourprojectskeletonHerearethestepsyoushouldtakeIrsquomgoingtogivetheseinstructionsinEnglishratherthanshowyouhowtotypethemsothatyouhavetofigureitout

1Copyskeletontoex472RenameeverythingwithNAMEtoex473ChangethewordNAMEinallthefilestoex474Finallyremoveallthepycfilestomakesureyoursquoreclean

ReferbacktoExercise46ifyougetstuckandifyoucanrsquotdothiseasilythen

maybepracticeitafewtimes

WarningRememberthatyourunthecommandnoseteststorunthetestsYoucanrunthemwithpython36ex47_testspybutitwonrsquotworkaseasilyandyoursquollhavetodoitforeachtestfile

Nextcreateasimplefileex47gamepywhereyoucanputthecodetotestThiswillbeaverysillylittleclassthatwewanttotestwiththiscodeinitClickheretoviewcodeimage

gamepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name

5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)Onceyouhavethatfile

changetheunittestskeletontothisClickheretoviewcodeimage

ex47_testspy

1fromnosetoolsimport

2fromex47gameimportRoom

3

4

5deftest_room()

6gold=Room(GoldRoom

7Thisroomhasgoldinityoucangrab

Theresa

8doortothenorth)

9assert_equal(goldnameGoldRoom)

10assert_equal(goldpaths)

11

12deftest_room_paths()

13center=Room(CenterTestroominthecenter)

14north=Room(NorthTestroominthenorth)

15south=Room(SouthTestroominthesouth)

16

17centeradd_paths(northnorthsouthsouth)

18assert_equal(centergo(north)north)

19assert_equal(centergo(south)south)

20

21deftest_map()

22start=Room(StartYoucangowestanddownahole)

23west=Room(TreesTherearetreeshereyoucango

east)

24down=Room(DungeonItsdarkdownhereyoucango

up)

25

26startadd_paths(westwestdowndown)

27westadd_paths(eaststart)

28downadd_paths(upstart)

29

30assert_equal(startgo(west)west)

31assert_equal(startgo(west)go(east)start)

32assert_equal(startgo(down)go(up)start)Thisfile

importstheRoomclassyoumadeintheex47gamemodulesothatyou

candotestsonitThereisthenasetofteststhatarefunctions

startingwithtest_Insideeachtestcasetherersquosabitofcodethat

makesaroomorasetofroomsandthenmakessuretheroomswork

thewayyouexpectthemtoworkIttestsoutthebasicroom

featuresthenthepathsthentriesoutawholemap

Theimportantfunctionshereareassert_equalwhichmakessurethatvariablesyouhavesetorpathsyouhavebuiltinaRoomareactuallywhatyouthinktheyareIfyougetthewrongresultthennosetestswillprintoutanerrormessagesoyoucangofigureitout

TestingGuidelinesFollowthisloosesetofguidelineswhenmakingyourtests

1TestfilesgointestsandarenamedBLAH_testspyotherwisenosetestswonrsquotrunthemThisalsokeepsyourtestsfromclashingwithyourothercode

2Writeonetestfileforeachmoduleyoumake3Keepyourtestcases(functions)shortbutdonotworryiftheyareabitmessyTestcasesareusuallykindofmessy

4EventhoughtestcasesaremessytrytokeepthemcleanandremoveanyrepetitivecodeyoucanCreatehelperfunctionsthatgetridofduplicatecodeYouwillthankmelaterwhenyoumakeachangeandthenhaveto

codeYouwillthankmelaterwhenyoumakeachangeandthenhavetochangeyourtestsDuplicatedcodewillmakechangingyourtestsmoredifficult

5FinallydonotgettooattachedtoyourtestsSometimesthebestwaytoredesignsomethingistojustdeleteitandstartover

WhatYouShouldSeeClickheretoviewcodeimage

Exercise47Session

$nosetests

---------------------------------------------------------------------

-

Ran3testsin0008s

OK

ThatrsquoswhatyoushouldseeifeverythingisworkingrightTrycausinganerrortoseewhatthatlookslikeandthenfixit

StudyDrills1Goreadaboutnosetestsmoreandalsoreadaboutalternatives2LearnaboutPythonrsquosldquodoctestsrdquoandseeifyoulikethembetter3Makeyourroommoreadvancedandthenuseittorebuildyourgameyetagainbutthistimeunittestasyougo

CommonStudentQuestionsIgetasyntaxerrorwhenIrunnosetestsIfyougetthatthenlookatwhattheerrorsaysandfixthatlineofcodeortheonesaboveitToolslikenosetestsarerunningyourcodeandthetestcodesotheywillfindsyntaxerrorsthesameasrunningPythonwill

Icanrsquotimportex47gameMakesureyoucreatetheex47__init__pyfileRefertoExercise46againtoseehowitrsquosdoneIfthatrsquosnottheproblemthendothisonmacOSLinuxexportPYTHONPATH=AndonWindowsClickheretoviewcodeimage

$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

FinallymakesureyoursquorerunningthetestswithnosetestsnotwithjustPython

IgetUserWarningwhenIrunnosetestsYouprobablyhavetwoversionsofPythoninstalledoryouarenrsquotusingdistributeGobackandinstalldistributeorpipasIdescribeinExercise46

Exercise48AdvancedUserInput

InpastgamesyouhandledtheuserrsquosinputbysimplyexpectingsetstringsIftheusertypedldquorunrdquoandexactlyldquorunrdquothenthegameworkedIftheytypedinsimilarphraseslikeldquorunfastrdquoitwouldfailWhatweneedisadevicethatletsuserstypephrasesinvariouswaysandthenconvertthatintosomethingthecomputerunderstandsForexamplewersquodliketohaveallofthesephrasesworkthesamebullopendoorbullopenthedoorbullgoTHROUGHthedoorbullpunchbearbullPunchTheBearintheFACEItshouldbealrightforausertowritesomethingalotlikeEnglishforyourgameandhaveyourgamefigureoutwhatitmeansTodothiswersquoregoingtowriteamodulethatdoesjustthatThismodulewillhaveafewclassesthatworktogethertohandleuserinputandconvertitintosomethingyourgamecanworkwithreliablyAsimplifiedversionoftheEnglishlanguagecouldincludethefollowingelementsbullWordsseparatedbyspacesbullSentencescomposedofthewordsbullGrammarthatstructuresthesentencesintomeaningThatmeansthebestplacetostartisfiguringouthowtogetwordsfromtheuserandwhatkindsofwordsthoseare

OurGameLexiconInourgamewehavetocreatealistofallowablewordscalledaldquolexiconrdquo

bullDirectionwordsnorthsoutheastwestdownupleftrightbackbullVerbsgostopkilleatbullStopwordstheinoffromatitbullNounsdoorbearprincesscabinetbullNumbersanystringof0through9charactersWhenwegettonounswehaveaslightproblemsinceeachroomcouldhaveadifferentsetofnounsbutletrsquosjustpickthissmallsettoworkwithfornowandimproveitlater

BreakingUpaSentenceOncewehaveourlexiconweneedawaytobreakupsentencessothatwecanfigureoutwhattheyareInourcasewersquovedefinedasentenceasldquowordsseparatedbyspacesrdquosowereallyjustneedtodothis

stuff=input(gt)

words=stuffsplit()Thatrsquosallwersquollworryaboutfornowbutthis

willworkreallywellforquiteawhile

LexiconTuples

LexiconTuplesOnceweknowhowtobreakupasentenceintowordswejusthavetogothroughthelistofwordsandfigureoutwhatldquotyperdquotheyareTodothatwersquoregoingtouseahandylittlePythonstructurecalledaldquotuplerdquoAtupleisnothingmorethanalistthatyoucanrsquotmodifyItrsquoscreatedbyputtingdatainsideasetofparentheseswithacommalikealistClickheretoviewcodeimage

first_word=(verbgo)

second_word=(directionnorth)

third_word=(directionwest)

sentence=[first_wordsecond_wordthird_word]

Thiscreatesapair(TYPEWORD)thatletsyoulookatthewordanddothingswithitThisisjustanexamplebutthatrsquosbasicallytheendresultYouwanttotakerawinputfromtheusercarveitintowordswithsplitanalyzethosewordstoidentifytheirtypesandfinallymakeasentenceoutofthem

ScanningInputNowyouarereadytowriteyourscannerThisscannerwilltakeastringofrawinputfromauserandreturnasentencethatrsquoscomposedofalistoftupleswiththe(TOKENWORD)pairingsIfawordisnrsquotpartofthelexiconthenitshouldstillreturntheWORDbutsettheTOKENtoanerrortokenTheseerrortokenswilltelluserstheymessedupHerersquoswhereitgetsfunIrsquomnotgoingtotellyouhowtodothisInsteadIrsquomgoingtowritealdquounittestrdquoandyouaregoingtowritethescannersothattheunittestworks

ExceptionsandNumbersThereisonetinythingIwillhelpyouwithfirstandthatrsquosconvertingnumbersInordertodothisthoughwersquoregoingtocheatanduseexceptionsAnexceptionisanerrorthatyougetfromsomefunctionyoumayhaverunWhathappensisyourfunctionldquoraisesrdquoanexceptionwhenitencountersanerrorthenyouhavetohandlethatexceptionForexampleifyoutypethisintoPythonyougetanexceptionClickheretoviewcodeimage

Exercise48PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtint(hell)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

ValueErrorinvalidliteralforint()withbase10hell

ThatValueErrorisanexceptionthattheint()functionthrewbecausewhatyouhandedint()isnotanumberTheint())functioncouldhavereturnedavaluetotellyouithadanerrorbutsinceitonlyreturnsintegersitrsquodhaveahardtimedoingthatItcanrsquotreturn-1sincethatrsquosanumberInsteadoftryingtofigureoutwhattoreturnwhentherersquosanerrortheint()functionraisestheValueErrorexceptionandyoudealwithitYoudealwithanexceptionbyusingthetryandexceptkeywordsex48_convertpy

1defconvert_number(s)

2try

3returnint(s)

4exceptValueError

5returnNoneYouputthecodeyouwanttoldquotryrdquoinside

thetryblockandthenyouputthecodetorunfortheerrorinside

theexceptInthiscasewewanttoldquotryrdquotocallint()onsomething

thatmightbeanumberIfthathasanerrorthenweldquocatchrdquoitand

returnNone

InyourscannerthatyouwriteyoushouldusethisfunctiontotestwhethersomethingisanumberYoushouldalsodoitasthelastthingyoucheckforbeforedeclaringthatwordanerrorword

ATestFirstChallengeTestfirstisaprogrammingtacticwhereyouwriteanautomatedtestthatpretendsthecodeworksthenyouwritethecodetomakethetestactuallyworkThismethodworkswhenyoucanrsquotvisualizehowthecodeisimplementedbutyoucanimaginehowyouhavetoworkwithitForexampleifyouknowhowyouneedtouseanewclassinanothermodulebutyoudonrsquotquiteknowhowtoimplementthatclassyetthenwritethetestfirstYouaregoingtotakeatestIgiveyouanduseittowritethecodethatmakesitworkTodothisexercisefollowthisprocedure1CreateonesmallpartofthetestIgiveyou

2Makesureitrunsandfailssoyouknowthatthetestisactuallyconfirmingafeatureworks

3Gotoyoursourcefilelexiconpyandwritethecodethatmakesthistestpass

4RepeatuntilyouhaveimplementedeverythinginthetestWhenyougettostep3itrsquosalsogoodtocombineourothermethodofwritingcode1Maketheldquoskeletonrdquofunctionorclassthatyouneed

2Writecommentsinsidedescribinghowthatfunctionworks3Writethecodethatdoeswhatthecommentsdescribe4Removeanycommentsthatjustrepeatthecode

ThismethodofwritingcodeiscalledldquopsuedocoderdquoandworkswellifyoudonrsquotknowhowtoimplementsomethingbutyoucandescribeitinyourownwordsCombiningtheldquotestfirstrdquowiththeldquopsuedocoderdquotacticswehavethissimpleprocessforprogramming1Writeabitoftestthatfails

2Writetheskeletonfunctionmoduleclassthetestneeds3Filltheskeletonwithcommentsinyourownwordsexplaininghowitworks

4Replacethecommentswithcodeuntilthetestpasses5Repeat

InthisexerciseyouwillpracticethismethodofworkingbymakingatestIgiveyourunagainstthelexiconpymodule

WhatYouShouldTestHereisthetestcasetestslexicon_testspythatyoushouldusebutdonrsquottypethisinyetClickheretoviewcodeimage

lexicon_testspy

1fromnosetoolsimport

2fromex48importlexicon

3

4

5deftest_directions()

6assert_equal(lexiconscan(north)[(direction

north)])

7result=lexiconscan(northsoutheast)

8assert_equal(result[(directionnorth)

9(directionsouth)

10(directioneast)])

11

12deftest_verbs()

13assert_equal(lexiconscan(go)[(verbgo)])

14result=lexiconscan(gokilleat)

15assert_equal(result[(verbgo)

16(verbkill)

17(verbeat)])

18

19

20deftest_stops()

21assert_equal(lexiconscan(the)[(stopthe)])

22result=lexiconscan(theinof)

23assert_equal(result[(stopthe)

24(stopin)

25(stopof)])

26

27

28deftest_nouns()

29assert_equal(lexiconscan(bear)[(nounbear)])

30result=lexiconscan(bearprincess)

31assert_equal(result[(nounbear)

32(nounprincess)])

33

34deftest_numbers()

35assert_equal(lexiconscan(1234)[(number1234)])

36result=lexiconscan(391234)

37assert_equal(result[(number3)

38(number91234)])

39

40

41deftest_errors()

42assert_equal(lexiconscan(ASDFADFASDF)

43[(errorASDFADFASDF)])

44result=lexiconscan(bearIASprincess)

45assert_equal(result[(nounbear)

46(errorIAS)

47(nounprincess)])Youwillwant

tocreateanewprojectusingtheprojectskeletonjustlikeyoudid

inExercise47Thenyoursquollneedtocreatethistestcaseandthe

lexiconpyfileitwilluseLookatthetopofthetestcasetosee

howitrsquosbeingimportedtofigureoutwhereitgoes

NextfollowtheprocedureIgaveyouandwritealittlebitofthetestcaseatatimeForexampleherersquoshowIrsquoddoit1WritetheimportatthetopGetthattowork

2Createanemptyversionofthefirsttestcasetest_directionsMakesurethatruns

3Writethefirstlineofthetest_directionstestcaseMakeitfail4Gotothelexiconpyfileandcreateanemptyscanfunction5Runthetestandmakesurescanisatleastrunningeventhoughitfails6Fillinpsuedocodecommentsforhowscanshouldworktomaketest_directionspass

7Writethecodethatmatchesthecommentsuntiltest_directionspasses

8Gobacktotest_directionsandwritetherestofthelines9Gobacktoscaninlexiconpyandworkonittomakethisnewtestcodepass

10Onceyoursquovedonethatyouhaveyourfirstpassingtestandyoumoveontothenexttest

AslongasyoukeepfollowingthisprocedureonelittlechunkatatimeyoucansuccessfullyturnalargeproblemintosmallersolvableproblemsItrsquoslikeclimbingamountainbyturningitintoabunchoflittlehills

StudyDrills1Improvetheunittesttomakesureyoutestmoreofthelexicon2Addtothelexiconandthenupdatetheunittest3MakesureyourscannerhandlesuserinputinanycapitalizationandcaseUpdatethetesttomakesurethisactuallyworks

4Findanotherwaytoconvertthenumber5Mysolutionwas37lineslongIsyourslongerShorter

CommonStudentQuestionsWhydoIkeepgettingImportErrorsImporterrorsareusuallycausedbyfourthings1Youdidnrsquotmakean__init__pyinadirectorythathasmodulesinit2Youareinthewrongdirectory3Youareimportingthewrongmodulebecauseyouspelleditwrong4YourPYTHONPATHisnrsquotsettosoyoucanrsquotloadmodulesfromyourcurrentdirectory

Whatrsquosthedifferencebetweentry-exceptandif-elseThe

try-exceptconstructisonlyusedforhandlingexceptionsthatmodulescanthrowItshouldneverbeusedasanalternativetoif-else

IsthereawaytokeepthegamerunningwhiletheuseriswaitingtotypeIrsquomassumingyouwanttohaveamonsterattackusersiftheydonrsquotreactquicklyenoughItispossiblebutitinvolvesmodulesandtechniquesthatareoutsideofthisbookrsquosdomain

Exercise49MakingSentences

WhatweshouldbeabletogetfromourlittlegamelexiconscannerisalistthatlookslikethisClickheretoviewcodeimage

Exercise49PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48importlexicon

gtgtgtlexiconscan(gonorth)

[(verbgo)(directionnorth)]

gtgtgtlexiconscan(killtheprincess)

[(verbkill)(stopthe)(nounprincess)]

gtgtgtlexiconscan(eatthebear)

[(verbeat)(stopthe)(nounbear)]

Thiswillalsoworkonlongersentencessuchaslexiconscan(openthedoorandsmackthebearinthenose)NowletusturnthisintosomethingthegamecanworkwithwhichwouldbesomekindofSentenceclassIfyouremembergradeschoolasentencecanbeasimplestructurelikeSubjectVerbObjectObviouslyitgetsmorecomplexthanthatandyouprobablydidmanydaysofannoyingsentencediagramsforEnglishclassWhatwewantistoturntheprecedinglistsoftuplesintoaniceSentenceobjectthathassubjectverbandobject

MatchandPeekTodothisweneedfivetools

1AwaytoloopthroughthelistofscannedwordsThatrsquoseasy2AwaytoldquomatchrdquodifferenttypesoftuplesthatweexpectinourSubjectVerbObjectsetup

3Awaytoldquopeekrdquoatapotentialtuplesowecanmakesomedecisions4Awaytoldquoskiprdquothingswedonotcareaboutlikestopwords5ASentenceobjecttoputtheresultsin

Wewillbeputtingthesefunctionsinamodulenamedex48parserinafilenamedex48parserpyinordertotestitWeusethepeekfunctiontosay

ldquolookatthenextelementinourtuplelistandthenmatchtotakeoneoffandworkwithitrdquo

TheSentenceGrammarBeforeyoucanwritethecodeyouneedtounderstandhowbasicEnglishsentencegrammarworksInourparserwewanttoproduceaSentenceobjectthathasthreeattributes

SentencesubjectThisisthesubjectofanysentencebutcoulddefaulttoldquoplayerrdquomostofthetimesinceasentenceofldquorunnorthrdquoisimplyingldquoplayerrunnorthrdquoThiswillbeanoun

SentenceverbThisistheactionofthesentenceInldquorunnorthrdquoitwouldbeldquorunrdquoThiswillbeaverb

SentenceobjectThisisanothernounthatreferstowhattheverbisdoneonInourgameweseparateoutdirectionswhichwouldalsobeobjectsInldquorunnorthrdquothewordldquonorthrdquowouldbetheobjectInldquohitbearrdquothewordldquobearrdquowouldbetheobject

OurparserthenhastousethefunctionswedescribedandgivenascannedsentenceconvertitintoanListofSentenceobjectstomatchtheinput

AWordonExceptionsYoubrieflylearnedaboutexceptionsbutnothowtoraisethemThiscodedemonstrateshowtodothatwiththeParserErroratthetopNoticethatitusesclassestogiveitthetypeofExceptionAlsonoticetheuseoftheraisekeywordtoraisetheexceptionInyourtestsyouwillwanttoworkwiththeseexceptionswhichIrsquollshowyouhowtodo

TheParserCodeIfyouwantanextrachallengestoprightnowandtrytowritethisbasedonjustmydescriptionIfyougetstuckyoucancomebackandseehowIdiditbuttryingtoimplementtheparseryourselfisgoodpracticeIwillnowwalkthroughthecodesoyoucanenteritintoyourex48parserpyWestarttheparserwiththeexceptionweneedforaparsingerrorClickheretoviewcodeimage

parserpy

1classParserError(Exception)

2pass

ThisishowyoumakeyourownParserErrorexceptionclassyoucanthrowNextweneedtheSentenceobjectwersquollcreateClickheretoviewcodeimage

parserpy

1classSentence(object)

2

3def__init__(selfsubjectverbobj)

4rememberwetake(nounprincess)tuplesand

convertthem

5selfsubject=subject[1]

6selfverb=verb[1]

7selfobject=obj[1]

TherersquosnothingspecialaboutthiscodesofarYoursquorejustmakingsimpleclassesInourdescriptionoftheproblemweneedafunctionthatcanpeekatalistofwordsandreturnwhattypeofworditisClickheretoviewcodeimage

parserpy

1defpeek(word_list)

2ifword_list

3word=word_list[0]

4returnword[0]

5else

6returnNoneWeneedthisfunctionbecausewersquollhaveto

makedecisionsaboutwhatkindofsentencewersquoredealingwithbased

onwhatthenextwordisThenwecancallanotherfunctionto

consumethatwordandcarryon

ToconsumeawordweusethematchfunctionwhichconfirmsthattheexpectedwordistherighttypetakesitoffthelistandreturnsthewordClickheretoviewcodeimage

parserpy

1defmatch(word_listexpecting)

2ifword_list

3word=word_listpop(0)

4

5ifword[0]==expecting

6returnword

7else

8returnNone

9else

10returnNoneAgainthisisfairlysimplebutmakesure

youunderstandthiscodeAlsomakesureyouunderstandwhyIrsquomdoing

itthiswayIneedtopeekatwordsinthelisttodecidewhatkind

ofsentenceIrsquomdealingwithandthenIneedtomatchthosewordsto

createmySentence

ThelastthingIneedisawaytoskipwordsthatarenrsquotusefultotheSentenceThesearethewordslabeledldquostopwordsrdquo(typestop)thatarewordslikeldquotherdquoldquoandrdquoandldquoardquoClickheretoviewcodeimage

parserpy

1defskip(word_listword_type)

2whilepeek(word_list)==word_type

3match(word_listword_type)Rememberthatskipdoesnrsquot

skiponeworditskipsasmanywordsofthattypeasitfindsThis

makesitsoifsomeonetypesldquoscreamatthebearrdquoyougetldquoscreamrdquo

andldquobearrdquo

ThatrsquosourbasicsetofparsingfunctionsandwiththatwecanactuallyparsejustaboutanytextwewantOurparserisverysimplethoughsotheremainingfunctionsareshortFirstwecanhandleparsingaverbClickheretoviewcodeimage

parserpy

1defparse_verb(word_list)

2skip(word_liststop)

3

4ifpeek(word_list)==verb

5returnmatch(word_listverb)

6else

7raiseParserError(Expectedaverbnext)Weskipany

stopwordsthenpeekaheadtomakesurethenextwordisaldquoverbrdquo

typeIfitrsquosnotthenraisetheParserErrortosaywhyIfitisa

ldquoverbrdquothenmatchitwhichtakesitoffthelistAsimilar

functionhandlessentenceobjectsClickheretoviewcodeimage

parserpy

1defparse_object(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==direction

8returnmatch(word_listdirection)

9else

10raiseParserError(Expectedanounordirectionnext)

Againskipthestopwordspeekaheadanddecideifthesentenceis

correctbasedonwhatrsquosthereIntheparse_objectfunctionthough

weneedtohandlebothldquonounrdquoandldquodirectionrdquowordsaspossible

objectsSubjectsarethensimilaragainbutsincewewanttohandle

theimpliedldquoplayerrdquonounwehavetousepeekClickheretoview

codeimage

parserpy

1defparse_subject(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==verb

8return(nounplayer)

9else

10raiseParserError(Expectedaverbnext)Withthat

alloutofthewayandreadyourfinalparse_sentencefunctionis

verysimpleClickheretoviewcodeimage

parserpy

1defparse_sentence(word_list)

2subj=parse_subject(word_list)

3verb=parse_verb(word_list)

4obj=parse_object(word_list)

5

6returnSentence(subjverbobj)

PlayingwiththeParserToseehowthisworksyoucanplaywithitlikethis

ToseehowthisworksyoucanplaywithitlikethisClickheretoviewcodeimage

Exercise49aPythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48parserimport

gtgtgtx=parse_sentence([(verbrun)(directionnorth)])

gtgtgtxsubject

player

gtgtgtxverb

run

gtgtgtxobject

north

gtgtgtx=parse_sentence([(nounbear)(verbeat)(stop

the)

(nounhoney)])

gtgtgtxsubject

bear

gtgtgtxverb

eat

gtgtgtxobject

honey

TrytomapsentencestothecorrectpairingsinasentenceForexamplehowwouldyousayldquothebearrunsouthrdquo

WhatYouShouldTestForExercise49writeacompletetestthatconfirmseverythinginthiscodeisworkingPutthetestintestsparser_testspysimilartothetestfilefromthelastexerciseThatincludesmakingexceptionshappenbygivingtheparserbadsentencesCheckforanexceptionbyusingthefunctionassert_raisesfromthenosedocumentationLearnhowtousethissoyoucanwriteatestthatisexpectedtofailwhichisveryimportantintestingLearnaboutthisfunction(andothers)byreadingthenosedocumentationWhenyouaredoneyoushouldknowhowthisbitofcodeworksandhowtowriteatestforotherpeoplersquoscodeeveniftheydonotwantyoutoTrustmeitrsquosaveryhandyskilltohave

StudyDrills

StudyDrills1Changetheparse_methodsandtrytoputthemintoaclassratherthanusethemjustasmethodsWhichdesigndoyoulikebetter

2Maketheparsermoreerror-resistantsothatyoucanavoidannoyingyourusersiftheytypewordsyourlexicondoesnrsquotunderstand

3Improvethegrammarbyhandlingmorethingslikenumbers4ThinkabouthowyoumightusethisSentenceclassinyourgametodomorefunthingswithauserrsquosinput

CommonStudentQuestionsIcanrsquotseemtomakeassert_raisesworkrightMakesureyouarewritingassert_raises(exceptioncallableparameters)andnotwritingassert_raises(exceptioncallable(parameters))Noticehowthesecondformiscallingthefunctionthenpassingtheresulttoassert_raiseswhichiswrongYouhavetopassthefunctiontocallanditsargumentstoassert_raises

Exercise50YourFirstWebsite

ThesefinalthreeexerciseswillbeveryhardandyoushouldtakeyourtimewiththemInthisfirstoneyoursquollbuildasimplewebversionofoneofyourgamesBeforeyouattemptthisexerciseyoumusthavecompletedExercise46successfullyandhaveaworkingpipinstalledsuchthatyoucaninstallpackagesandknowhowtomakeaskeletonprojectdirectoryIfyoudonrsquotrememberhowtodothisgobacktoExercise46anddoitalloveragain

InstallingflaskBeforecreatingyourfirstwebapplicationyoursquollfirstneedtoinstalltheldquowebframeworkrdquocalledflaskThetermldquoframeworkrdquogenerallymeansldquosomepackagethatmakesiteasierformetodosomethingrdquoIntheworldofwebapplicationspeoplecreateldquowebframeworksrdquotocompensateforthedifficultproblemstheyrsquoveencounteredwhenmakingtheirownsitesTheysharethesecommonsolutionsintheformofapackageyoucandownloadtobootstrapyourownprojectsInourcasewersquollbeusingtheflaskframeworkbuttherearemanymanymanyothersyoucanchoosefromFornowlearnflaskthenbranchouttoanotheronewhenyoursquoreready(orjustkeepusingflasksinceitrsquosgoodenough)UsingpipinstallflaskClickheretoviewcodeimage

$sudopipinstallflask

[sudo]passwordforzedshaw

Downloadingunpackingflask

Runningsetuppyegg_infoforpackageflask

Installingcollectedpackagesflask

Runningsetuppyinstallforflask

Successfullyinstalledflask

Cleaningup

ThiswillworkonLinuxandmacOScomputersbutonWindowsjustdropthesudopartofthepipinstallcommandanditshouldworkIfnotgobacktoExercise46andmakesureyoucandoitreliably

MakeaSimpleldquoHelloWorldrdquoProject

NowyoursquoregoingtomakeaninitialverysimpleldquoHelloWorldrdquowebapplicationandprojectdirectoryusingflaskFirstmakeyourprojectdirectoryClickheretoviewcodeimage

$cdprojects

$mkdirgothonweb

$cdgothonweb

$mkdirbingothonwebtestsdocstemplates

$touchgothonweb__init__py

$touchtests__init__py

YoursquollbetakingthegamefromExercise43andmakingitintoawebapplicationsothatrsquoswhyyoursquorecallingitgothonwebBeforeyoudothatweneedtocreatethemostbasicflaskapplicationpossiblePutthefollowingcodeintoapppyClickheretoviewcodeimage

ex50py

1fromflaskimportFlask

2app=Flask(__name__)

3

4approute()

5defhello_world()

6returnHelloWorld

7

8if__name__==__main__

9apprun()ThenruntheapplicationlikethisClickhereto

viewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)Finally

useyourwebbrowserandgotohttplocalhost5000andyoushould

seetwothingsFirstinyourbrowseryoursquollseeHelloworld

SecondyoursquollseeyourTerminalwithnewoutputlikethisClick

heretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

127001ndashndash[22Feb2017142850]GETHTTP11200ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

ThosearelogmessagesthatflaskprintsoutsoyoucanseethattheserverisworkingandwhatthebrowserisdoingbehindthescenesThelogmessageshelpyoudebugandfigureoutwhenyouhaveproblemsForexampleitrsquossayingthatyourbrowsertriedtogetfaviconicobutthatfiledidnrsquotexistsoit

returnedthe404NotFoundstatuscodeIhavenrsquotexplainedthewayanyofthiswebstuffworksyetbecauseIwanttogetyousetupandreadytorollsothatIcanexplainitbetterinthenexttwoexercisesToaccomplishthisIrsquollhaveyoubreakyourflaskapplicationinvariouswaysandthenrestructureitsothatyouknowhowitrsquossetup

WhatrsquosGoingOnHerersquoswhatrsquoshappeningwhenyourbrowserhitsyourapplication

1YourbrowsermakesanetworkconnectiontoyourowncomputerwhichiscalledlocalhostandisastandardwayofsayingldquowhatevermyowncomputeriscalledonthenetworkrdquoItalsousesport5000

2OnceitconnectsitmakesanHTTPrequesttotheapppyapplicationandasksfortheURLwhichiscommonlythefirstURLonanywebsite

3InsideapppyyoursquovegotalistofURLsandwhatfunctionstheymatchTheonlyonewehaveistheindexmappingThismeansthatwheneversomeonegoestowithabrowserflaskwillfindthedefindexandrunittohandletherequest

4NowthatflaskhasfounddefindexitcallsittoactuallyhandletherequestThisfunctionrunsandsimplyreturnsastringforwhatflaskshouldsendtothebrowser

5Finallyflaskhashandledtherequestandsendsthisresponsetothebrowserwhichiswhatyouareseeing

MakesureyoureallyunderstandthisDrawupadiagramofhowthisinformationflowsfromyourbrowsertoflaskthentodefindexandbacktoyourbrowser

FixingErrorsFirstdeleteline8whereyouassignthegreetingvariablethenhitrefreshinyourbrowserThenuseCTRL-CtokillflaskandstartitagainOnceitrsquosrunningagainrefreshyourbrowserandyoushouldseeanldquoInternalServerErrorrdquoBackinyourTerminalyoursquollseethis([VENV]isthepathtoyourvenvsdirectory)Clickheretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

[2017ndash02ndash22143554256]ERRORinappExceptionon[GET]

Traceback(mostrecentcalllast)

File[VENV]site-packagesflaskapppy

line1982inwsgi_app

response=selffull_dispatch_request()

File[VENV]site-packagesflaskapppy

line1614infull_dispatch_request

rv=selfhandle_user_exception(e)

File[VENV]site-packagesflaskapppy

line1517inhandle_user_exception

reraise(exc_typeexc_valuetb)

File[VENV]site-packagesflask_compatpy

line33inreraise

raisevalue

File[VENV]site-packagesflaskapppy

line1612infull_dispatch_request

rv=selfdispatch_request()

File[VENV]site-packagesflaskapppy

line1598indispatch_request

returnselfview_functions[ruleendpoint](reqview_args)

Fileapppyline8inindex

returnrender_template(indexhtmlgreeting=greeting)

NameErrornamegreetingisnotdefined

127001ndashndash[22Feb2017143554]GETHTTP11500ndash

ThisworkswellenoughbutyoucanalsorunflaskinldquodebuggermoderdquoThiswillgiveyouabettererrorpageandmoreusefulinformationTheproblemwithdebuggermodeisitrsquosnotsafetorunontheinternetsoyouhavetoexplicitlyturnitonlikethisClickheretoviewcodeimage

(lpthw)$exportFLASK_DEBUG=1

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

Restartingwithstat

Debuggerisactive

Debuggerpincode222ndash752ndash342

Afterthisyouhitrefreshinyourbrowserandyougetamuchmoredetailedpagewithinformationyoucanusetodebugtheapplicationandaliveconsoletoworkwithtofindoutmore

WarningItrsquostheflasklivedebuggingconsoleandtheimprovedoutputthatmakesdebugmodesodangerousontheinternetWiththisinformationanattackercancompletelycontrolyourmachineremotelyIfyoueverdoplaceyourwebapplicationontheinternetdonotactivatedebuggermodeInfactIwouldavoid

makingFLASK_DEBUGeasytoactivateItrsquostemptingtosimplyhackthisstartupsothatyousaveastepduringdevelopmentbutthenthathackwillgetontoyourwebserveranditrsquollturnintoarealhacknotjustsomethinglazyyoudidonenightwhenyouweretired

CreateBasicTemplatesYoucanbreakyourflaskapplicationbutdidyounoticethatldquoHelloWorldrdquoisnrsquotaverygoodHTMLpageThisisawebapplicationandassuchitneedsaproperHTMLresponseTodothatyouwillcreateasimpletemplatethatsaysldquoHelloWorldrdquoinabiggreenfontThefirststepistocreateatemplatesindexhtmlfilethatlookslikethisClickheretoviewcodeimage

indexhtml

lthtmlgt

ltheadgt

lttitlegtGothonsOfPlanetPercal25lttitlegt

ltheadgt

ltbodygt

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

ltbodygt

lthtmlgtIfyouknowwhatHTMListhenthisshouldlookfairly

familiarIfnotresearchHTMLandtrywritingafewwebpagesby

handsoyouknowhowitworksThisHTMLfilehoweverisa

templatewhichmeansthatflaskwillfillinldquoholesrdquointhetext

dependingonvariablesyoupassintothetemplateEveryplaceyou

see$greetingwillbeavariableyoursquollpasstothetemplatethat

altersitscontents

TomakeyourapppydothisyouneedtoaddsomecodetotellflaskwheretoloadthetemplateandtorenderitTakethatfileandchangeitlikethisClickheretoviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3

4app=Flask(__name__)

5

6approute()

7defindex()

8greeting=HelloWorld

9returnrender_template(indexhtmlgreeting=greeting)

10

11if__name__==__main__

12apprun()Paycloseattentiontothenewrendervariable

andhowIchangedthelastlineofindexGETsoitreturns

renderindex()passinginyourgreetingvariable

OnceyouhavethatinplacereloadthewebpageinyourbrowserandyoushouldseeadifferentmessageingreenYoushouldalsobeabletodoaViewSourceonthepageinyourbrowsertoseethatitisvalidHTMLThismayhaveflownbyyouveryfastsoletmeexplainhowatemplateworks1Inyourapppyyoursquoveimportedanewfunctionnamedrender_templateatthetop

2Thisrender_templateknowshowtoloadhtmlfilesoutofthetemplatesdirectorybecausethatisthedefaultmagicsettingforaflaskapplication

3Laterinyourcodewhenthebrowserhitsthedefindexinsteadofjustreturningthestringgreetingyoucallrender_templateandpassthegreetingtoitasavariable

4Thisrender_templatemethodthenloadsthetemplatesindexhtmlfile(eventhoughyoudidnrsquotexplicitlysaytemplates)andprocessesit

5InthistemplatesindexhtmlfileyouhavewhatlookslikenormalHTMLbutthentherersquosldquocoderdquoplacedbetweentwokindsofmarkersOneiswhichmarkspiecesofldquoexecutablecoderdquo(if-statementsfor-loopsetc)TheotheriswhichmarksvariablestobeconvertedintotextandplacedintotheHTMLoutputTheexecutablecodedoesnrsquotshowupintheHTMLTolearnmoreaboutthistemplatelanguagereadtheJinja2documentation

TogetdeeperintothischangethegreetingvariableandtheHTMLtoseewhateffectithasAlsocreateanothertemplatenamedtemplatesfoohtmlandrenderthatlikebefore

StudyDrills1Readthedocumentationathttpflaskpocooorgdocs012whichisthesameastheflaskproject

2Experimentwitheverythingyoucanfindthereincludingtheirexamplecode

3ReadaboutHTML5andCSS3andmakesomeotherhtmlandcssfilesforpractice

4IfyouhaveafriendwhoknowsDjangoandiswillingtohelpyouthenconsiderdoingExercises5051and52inDjangoinsteadtoseewhatthatrsquoslike

CommonStudentQuestionsIcanrsquotseemtoconnecttohttplocalhost5000Tryhttp1270015000instead

WhatisthedifferencebetweeflaskandwebpyNodifferenceIsimplyldquolockedrdquowebpyataparticularversionsothatitwouldbeconsistentforstudentsthennameditflaskLaterversionsofwebpymightbedifferentfromthisversion

Icanrsquotfindindexhtml(orjustaboutanything)YouprobablyaredoingcdbinfirstandthentryingtoworkwiththeprojectDonotdothisAllofthecommandsandinstructionsassumeyouareonedirectoryabovebinsoifyoucanrsquottypepython36apppythenyouareinthewrongdirectory

Whydoweassigngreeting=greetingwhenwecallthetemplateYouarenotassigningtogreetingYouaresettinganamedparametertogivetothetemplateItrsquossortofanassignmentbutitonlyaffectsthecalltothetemplatefunction

Icanrsquotuseport5000onmycomputerYouprobablyhaveananti-virusprograminstalledthatisusingthatportTryadifferentport

AfterinstallingflaskIgetImportErrorNomodulenamedwebYoumostlikelyhavemultipleversionsofpythoninstalledandareusingthewrongoneoryoudidnrsquotdotheinstall

correctlybecauseofanoldversionofpipTryuninstallingflaskandreinstallingitIfthatdoesnrsquotworkmaketriplesureyoursquoreusingtherightversionofpython

Exercise51GettingInputfromaBrowser

WhileitrsquosexcitingtoseethebrowserdisplayldquoHelloWorldrdquoitrsquosevenmoreexcitingtolettheusersubmittexttoyourapplicationfromaformInthisexercisewersquollimproveourstarterwebapplicationbyusingformsandstoringinformationaboutusersintotheirldquosessionsrdquo

HowtheWebWorksTimeforsomeboringstuffYouneedtounderstandabitmoreabouthowthewebworksbeforeyoucanmakeaformThisdescriptionisnrsquotcompletebutitrsquosaccurateandwillhelpyoufigureoutwhatmightbegoingwrongwithyourapplicationAlsocreatingformswillbeeasierifyouknowwhattheydoIrsquollstartwithasimplediagramthatshowsyouthedifferentpartsofawebrequestandhowtheinformationflows

IrsquovelabeledthelineswithletterssoIcanwalkyouthrougharegularrequestprocess1Youtypeintheurlhttptestcomintoyourbrowseranditsendstherequestonline(A)toyourcomputerrsquosnetworkinterface

2Yourrequestgoesoutovertheinternetonline(B)andthentotheremotecomputeronline(C)wheremyserveracceptstherequest

3Oncemycomputeracceptsitmywebapplicationgetsitonline(D)andmyPythoncoderunstheindexGEThandler

4TheresponsecomesoutofmyPythonserverwhenIreturnitandit

goesbacktoyourbrowseroverline(D)again5Theserverrunningthissitetakestheresponseoffline(D)thensendsitbackovertheinternetonline(C)

6Theresponsefromtheserverthencomesofftheinternetonline(B)andyourcomputerrsquosnetworkinterfacehandsittoyourbrowseronline(A)

7FinallyyourbrowserthendisplaystheresponseInthisdescriptionthereareafewtermsyoushouldknowsothatyouhaveacommonvocabularytoworkwithwhentalkingaboutyourwebapplicationBrowserThesoftwarethatyoursquoreprobablyusingeverydayMostpeopledonrsquotknowwhatabrowserreallydoesTheyjustcallbrowsersldquotheinternetrdquoItsjobistotakeaddresses(likehttptestcom)youtypeintotheURLbarthenusethatinformationtomakerequeststotheserveratthataddress

AddressThisisnormallyaURL(UniformResourceLocator)likehttptestcomandindicateswhereabrowsershouldgoThefirstparthttpindicatestheprotocolyouwanttouseinthiscaseldquoHyper-TextTransportProtocolrdquoYoucanalsotryftpibiblioorgtoseehowldquoFileTransportProtocolrdquoworksThehttptestcompartistheldquohostnamerdquoahumanreadableaddressyoucanrememberandwhichmapstoanumbercalledanIPaddresssimilartoatelephonenumberforacomputerontheinternetFinallyURLscanhaveatrailingpathlikethebookpartofhttptestcombookwhichindicatesafileorsomeresourceontheservertoretrievewitharequestTherearemanyotherpartsbutthosearethemainones

ConnectionOnceabrowserknowswhatprotocolyouwanttouse(http)whatserveryouwanttotalkto(httptestcom)andwhatresourceonthatservertogetitmustmakeaconnectionThebrowsersimplyasksyouroperatingsystem(OS)toopenaldquoportrdquotothecomputerusuallyport80WhenitworkstheOShandsbacktoyourprogramsomethingthatworkslikeafilebutisactuallysendingandreceivingbytesoverthenetworkwiresbetweenyourcomputerandtheothercomputerathttptestcomThisisalsothesamethingthathappenswithhttplocalhost8080butinthiscaseyoursquoretellingthebrowsertoconnecttoyourowncomputer(localhost)anduseport8080ratherthanthedefaultof80Youcouldalsodohttptestcom80andgetthesameresultexceptyoursquoreexplicitlysayingtouseport80insteadoflettingitbethatbydefault

RequestYourbrowserisconnectedusingtheaddressyougaveNowitneedstoaskfortheresourceitwants(oryouwant)ontheremoteserverIfyougavebookattheendoftheURLthenyouwantthefile(resource)atbookandmostserverswillusetherealfilebookindexhtmlbutpretenditdoesnrsquotexistWhatthebrowserdoestogetthisresourceissendarequesttotheserverIwonrsquotgetintoexactlyhowitdoesthisbutjustunderstandthatithastosendsomethingtoquerytheserverfortherequestTheinterestingthingisthattheseldquoresourcesrdquodonrsquothavetobefilesForinstancewhenthebrowserinyourapplicationasksforsomethingtheserverisreturningsomethingyourPythoncodegenerated

ServerTheserveristhecomputerattheendofabrowserrsquosconnectionthatknowshowtoansweryourbrowserrsquosrequestsforfilesresourcesMostwebserversjustsendfilesandthatrsquosactuallythemajorityoftrafficButyoursquoreactuallybuildingaserverinPythonthatknowshowtotakerequestsforresourcesandthenreturnstringsthatyoucraftusingPythonWhenyoudothiscraftingyouarepretendingtobeafiletothebrowserbutreallyitrsquosjustcodeAsyoucanseefromExercise50italsodoesnrsquottakemuchcodetocreatearesponse

ResponseThisistheHTML(CSSJavaScriptorimages)yourserverwantstosendbacktothebrowserastheanswertothebrowserrsquosrequestInthecaseoffilesitjustreadsthemoffthediskandsendsthemtothebrowserbutitwrapsthecontentsofthediskinaspecialldquoheaderrdquosothebrowserknowswhatitrsquosgettingInthecaseofyourapplicationyoursquorestillsendingthesamethingincludingtheheaderbutyougeneratethatdataontheflywithyourPythoncode

ThatisthefastestcrashcourseinhowawebbrowseraccessesinformationonserversontheinternetItshouldworkwellenoughforyoutounderstandthisexercisebutifnotreadaboutitasmuchasyoucanuntilyougetitAreallygoodwaytodothatistotakethediagramandbreakdifferentpartsofthewebapplicationyoudidinExercise50Ifyoucanbreakyourwebapplicationinpredictablewaysusingthediagramyoursquollstarttounderstandhowitworks

HowFormsWorkThebestwaytoplaywithformsistowritesomecodethatacceptsformdataandthenseewhatyoucandoTakeyourapppyfileandmakeitlooklikethis

Clickheretoviewcodeimage

form_testpy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hello)

8defindex()

9name=requestargsget(nameNobody)

10

11ifname

12greeting=fHelloname

13else

14greeting=HelloWorld

15

16returnrender_template(indexhtmlgreeting=greeting)

17

18if__name__==__main__

19apprun()Restartit(hitCTRL-Candthenrunitagain)to

makesureitloadsagainthenwithyourbrowsergoto

httplocalhost5000hellowhichshoulddisplayldquoIjustwantedto

sayHelloNobodyrdquoNextchangetheURLinyourbrowserto

httplocalhost5000helloname=Frankandyoursquollseeitsay

ldquoHelloFrankrdquoFinallychangethename=Frankparttobeyourname

Nowitrsquossayinghellotoyou

LetrsquosbreakdownthechangesImadetoyourscript1InsteadofjustastringforgreetingIrsquomnowusingrequestargstogetdatafromthebrowserThisisasimpledictthatcontainstheformvaluesaskey=valuepairs

2Ithenconstructthegreetingfromthenewnamewhichshouldbeveryfamiliartoyoubynow

3EverythingelseaboutthefileisthesameasbeforeYoursquorealsonotrestrictedtojustoneparameterontheURLChangethisexampletogivetwovariableslikethishttplocalhost5000helloname=Frankampgreet=HolaThenchangethecodetogetnameandgreetlikethisClickheretoviewcodeimage

greet=requestargsget(greetHello)

greeting=fgreetname

greeting=fgreetname

YoushouldalsotrynotgivingthegreetandnameparametersontheURLYoursquollsimplysendyourbrowsertohttplocalhost5000hellotoseethattheindexnowdefaultstoldquoNobodyrdquofornameandldquoHellordquoforgreet

CreatingHTMLFormsPassingtheparametersontheURLworksbutitrsquoskindofuglyandnoteasytouseforregularpeopleWhatyoureallywantisaldquoPOSTformrdquowhichisaspecialHTMLfilethathasaltformgttaginitThisformwillcollectinformationfromtheuserthensendittoyourwebapplicationjustlikeyoudidaboveLetrsquosmakeaquickonesoyoucanseehowitworksHerersquosthenewHTMLfileyouneedtocreateintemplateshello_formhtmlClickheretoviewcodeimage

hello_formhtml

lthtmlgt

ltheadgt

lttitlegtSampleWebFormlttitlegt

ltheadgt

ltbodygt

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

ltbodygt

lthtmlgtYoushouldthenchangeapppytolooklikethisClickhere

toviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hellomethods=[POSTGET])

8defindex()

9greeting=HelloWorld

10

11ifrequestmethod==POST

12name=requestform[name]

13greet=requestform[greet]

14greeting=fgreetname

15returnrender_template(indexhtmlgreeting=greeting)

16else

17returnrender_template(hello_formhtml)

18

19

20if__name__==__main__

21apprun()Onceyoursquovegotthosewrittenupsimplyrestart

thewebapplicationagainandhititwithyourbrowserlikebefore

ThistimeyoursquollgetaformaskingyouforldquoAGreetingrdquoandldquoYourNamerdquoWhenyouhittheSubmitbuttonontheformitwillgiveyouthesamegreetingyounormallygetbutthistimelookattheURLinyourbrowserSeehowitrsquoshttplocalhost5000helloeventhoughyousentinparametersThepartofthehello_formhtmlfilethatmakesthisworkisthelinewithltformaction=hellomethod=POSTgtThistellsyourbrowserto1Collectdatafromtheuserusingtheformfieldsinsidetheform

2SendthemtotheserverusingaPOSTtypeofrequestwhichisjustanotherbrowserrequestthatldquohidesrdquotheformfields

3SendthattothehelloURL(asshownintheaction=hellopart)

YoucanthenseehowthetwoltinputgttagsmatchthenamesofthevariablesinyournewcodeAlsonoticethatinsteadofjustaGETmethodinsideclassindexIhaveanothermethodPOSTHowthisnewapplicationworksisasfollows1Yourrequestgoestoindex()likenormalexceptnowthereisanif-statementthatcheckstherequestmethodforeitherPOSTorGETmethodsThisishowthebrowsertellsapppythatarequestiseitheraformsubmissionorURLparameters

2IfrequestmethodisPOSTthenyouprocesstheformasifitwerefilledoutandsubmittedreturningthepropergreeting

3Ifrequestmethodisanythingelsethenyousimplyreturnthehello_formhtmlfortheusertofillout

AsanexercisegointothetemplatesindexhtmlfileandaddalinkbacktojusthellosothatyoucankeepfillingouttheformandseeingtheresultsMakesureyoucanexplainhowthislinkworksandhowitrsquoslettingyoucyclebetweentemplatesindexhtmlandtemplateshello_formhtmlandwhatrsquosbeingruninsidethislatestPythoncode

CreatingaLayoutTemplateWhenyouworkonyourgameinthenextexerciseyoursquollneedtomakeabunchoflittleHTMLpagesWritingafullwebpageeachtimewillquicklybecometediousLuckilyyoucancreatealdquolayoutrdquotemplateorakindofshellthatwillwrapallyourotherpageswithcommonheadersandfootersGoodprogrammerstrytoreducerepetitionsolayoutsareessentialforbeingagoodprogrammerChangetemplatesindexhtmltobelikethisClickheretoviewcodeimage

index_laid_outhtml

extendslayouthtml

blockcontent

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

endblock

Thenchangetemplateshello_formhtmltobelikethisClickheretoviewcodeimage

hello_form_laid_outhtml

extendslayouthtml

blockcontent

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

endblock

AllwersquoredoingisstrippingouttheldquoboilerplaterdquoatthetopandthebottomwhichisalwaysoneverypageWersquollputthatbackintoasingletemplateslayouthtmlfilethathandlesitforusfromnowonOnceyouhavethosechangescreateatemplateslayouthtmlfilewiththisinitClickheretoviewcodeimage

layouthtml

lthtmlgt

ltheadgt

lttitlegtGothonsFromPlanetPercal25lttitlegt

ltheadgt

ltbodygt

blockcontent

endblock

ltbodygt

lthtmlgtThisfilelookslikearegulartemplateexceptthatitrsquos

goingtobepassedthecontentsoftheothertemplatesandusedto

wrapthemAnythingyouputinheredoesnrsquotneedtobeintheother

templatesYourotherHTMLtemplateswillbeinsertedintothe

blockcontentsectionflaskknowstousethislayouthtmlasthe

layoutbecauseyouputextendslayouthtmlatthetopofyour

templates

WritingAutomatedTestsforFormsItrsquoseasytotestawebapplicationwithyourbrowserbyjusthittingrefreshbutcomeonwersquoreprogrammershereWhydosomerepetitivetaskwhenwecanwritesomecodetotestourapplicationWhatyoursquoregoingtodonextiswritealittletestforyourwebapplicationformbasedonwhatyoulearnedinExercise

47IfyoudonrsquotrememberExercise47readitagainCreateanewfilenamedtestsapp_testspywiththisClickheretoviewcodeimage

app_testspy

1fromnosetoolsimport

2fromappimportapp

3

4appconfig[TESTING]=True

5web=apptest_client()

6

7deftest_index()

8rv=webget(follow_redirects=True)

9assert_equal(rvstatus_code404)

10

11rv=webget(hellofollow_redirects=True)

12assert_equal(rvstatus_code200)

13assert_in(bFillOutThisFormrvdata)

14

15data=nameZedgreetHola

16rv=webpost(hellofollow_redirects=Truedata=data)

17assert_in(bZedrvdata)

18assert_in(bHolarvdata)Finallyusenoseteststorun

thistestsetupandtestyourwebapplication$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0059s

OK

WhatIrsquomdoinghereisIrsquomactuallyimportingthewholeapplicationfromtheapppymodulethenrunningitmanuallyTheflaskframeworkhasaverysimpleAPIforprocessingrequestswhichlookslikethisClickheretoviewcodeimage

data=nameZedgreetHola

rv=webpost(hellofollow_redirects=Truedata=data)Thismeans

youcansendaPOSTrequestusingthepost()methodandthengiveit

theformdataasadictEverythingelseworksthesameastesting

webget()requests

Inthetestsapp_testspyautomatedtestIrsquomfirstmakingsuretheURLreturnsaldquo404NotFoundrdquoresponsesinceitactuallydoesnrsquotexistThenIrsquomcheckingthathelloworkswithbothaGETandaPOSTformFollowing

thetestshouldbefairlysimpleevenifyoumightnottotallyknowwhatrsquosgoingonTakesometimestudyingthislatestapplicationespeciallyhowtheautomatedtestingworksMakesureyouunderstandhowIimportedtheapplicationfromapppyandranitdirectlyfortheautomatedtestThisisanimportanttrickthatwillleadtomorelearning

StudyDrills1ReadevenmoreaboutHTMLandgivethesimpleformabetterlayoutIthelpstodrawwhatyouwanttodoonpaperandthenimplementitwithHTML

2Thisoneishardbuttrytofigureouthowyoursquoddoafileuploadformsothatyoucanuploadanimageandsaveittothedisk

3Thisisevenmoremind-numbingbutgofindtheHTTPRFC(whichisthedocumentthatdescribeshowHTTPworks)andreadasmuchofitasyoucanItisreallyboringbutcomesinhandyonceinawhile

4ThiswillalsobereallydifficultbutseeifyoucanfindsomeonetohelpyousetupawebserverlikeApacheNginxorthttpdTrytoserveacoupleofyourhtmlandcssfileswithitjusttoseeifyoucanDonrsquotworryifyoucanrsquotWebserverskindofsuck

5Takeabreakafterthisandjusttrymakingasmanydifferentwebapplicationsasyoucan

BreakingItThisisagreatplacetofigureouthowtobreakwebapplicationsYoushouldexperimentwiththefollowing

1HowmuchdamagecanyoudowiththeFLASK_DEBUGsettingonBecarefulthatyoudonrsquotwipeyourselfoutdoingthis

2LetrsquossayyoudonrsquothavedefaultparametersfortheformsWhatcouldgowrong

3YoursquorecheckingforPOSTandthenldquoanythingelserdquoYoucanusethecurlcommandlinetooltogeneratedifferentrequesttypesWhathappens

Exercise52TheStartofYourWebGame

WersquorecomingtotheendofthebookandinthisexerciseIrsquomgoingtoreallychallengeyouWhenyoursquoredoneyoursquollbeareasonablycompetentPythonbeginnerYoursquollstillneedtogothroughafewmorebooksandwriteacouplemoreprojectsbutyoursquollhavetheskillstocompletethemTheonlyobstacleswillbetimemotivationandresourcesInthisexercisewewonrsquotmakeacompletegamebutinsteadwersquollmakeanldquoenginerdquothatcanrunthegamefromExercise47inthebrowserThiswillinvolverefactoringExercise43mixinginthestructurefromExercise47addingautomatedtestsandfinallycreatingawebenginethatcanrunthegamesThisexercisewillbehugeandIpredictyoucouldspendanywherefromaweektomonthsonitbeforemovingonItrsquosbesttoattackitinlittlechunksanddoabitanighttakingyourtimetomakeeverythingworkbeforemovingon

RefactoringtheExercise43GameYoursquovebeenalteringthegothonwebprojectfortwoexercisesandyoursquolldoitonemoretimeinthisexerciseTheskillyoursquorelearningiscalledldquorefactoringrdquoorasIliketocallitldquofixingstuffrdquoRefactoringisatermprogrammersusetodescribetheprocessoftakingoldcodeandchangingittohavenewfeaturesorjusttocleanitupYoursquovebeendoingthiswithoutevenknowingitasitrsquossecondnaturetobuildingsoftwareWhatyoursquolldointhispartistaketheideasfromExercise47ofatestableldquomaprdquoofRoomsandthegamefromExercise43andcombinethemtogethertocreateanewgamestructureItwillhavethesamecontentjustldquorefactoredrdquotohaveabetterstructureThefirststepistograbthecodefromex47gamepycopyittogothonwebplanispherepycopythetestsex47_testspyfiletotestsplanisphere_testspyandrunnosetestsagaintomakesureitkeepsworkingThewordldquoplanisphererdquoisjustasynonymforldquomaprdquowhichavoidsPythonrsquosbuilt-inmapfunctionThethesaurusisyourfriend

WarningFromnowonIwonrsquotshowyoutheoutputofatestrunJustassumethatyoushouldbedoingitanditrsquolllookliketheprecedingunlessyouhaveanerror

OnceyouhavethecodefromExercise47copiedoveritrsquostimetorefactorittohavetheExercise43mapinitIrsquomgoingtostartoffbylayingdownthebasicstructureandthenyoursquollhaveanassignmenttomaketheplanispherepyfileandtheplanisphere_testspyfilecompleteLayoutthebasicstructureofthemapusingtheRoomclassasitisnowClickheretoviewcodeimage

planispherepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)

13

14

15central_corridor=Room(CentralCorridor

16

17TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyed

18yourentirecrewYouarethelastsurvivingmemberandyour

last

19missionistogettheneutrondestructbombfromtheWeapons

Armoryput

20itinthebridgeandblowtheshipupaftergettingintoan

escapepod

21

22YourerunningdownthecentralcorridortotheWeaponsArmory

whena

23Gothonjumpsoutredscalyskindarkgrimyteethandevil

clown

24costumeflowingaroundhishatefilledbodyHesblocking

thedoorto

25theArmoryandabouttopullaweapontoblastyou

26)

27

28

29laser_weapon_armory=Room(LaserWeaponArmory

30

31LuckyforyoutheymadeyoulearnGothoninsultsinthe

academyYou

32telltheoneGothonjokeyouknowLbhezbgurevffbsngjura

furfvgf

33nebhaqgurubhfrfurfvgfnebhaqgurubhfrTheGothon

stopstries

34nottolaughthenbustsoutlaughingandcantmoveWhile

hes

35laughingyourunupandshoothimsquareintheheadputting

himdown

36thenjumpthroughtheWeaponArmorydoor

37

38YoudoadiverollintotheWeaponArmorycrouchandscanthe

roomfor

39moreGothonsthatmightbehidingItsdeadquiettoo

quietYou

40standupandruntothefarsideoftheroomandfindthe

neutronbomb

41initscontainerTheresakeypadlockontheboxandyou

needthe

42codetogetthebomboutIfyougetthecodewrong10times

thenthe

43lockclosesforeverandyoucantgetthebombThecodeis3

digits

44)

45

46

47the_bridge=Room(TheBridge

48

49Thecontainerclicksopenandthesealbreakslettinggas

outYou

50grabtheneutronbombandrunasfastasyoucantothebridge

whereyou

51mustplaceitintherightspot

52

53YouburstontotheBridgewiththenetrondestructbombunder

yourarm

54andsurprise5Gothonswhoaretryingtotakecontrolofthe

shipEach

55ofthemhasanevenuglierclowncostumethanthelastThey

havent

56pulledtheirweaponsoutyetastheyseetheactivebomb

underyourarm

57anddontwanttosetitoff

58)

59

60

61escape_pod=Room(EscapePod

62

63Youpointyourblasteratthebombunderyourarmandthe

Gothonsput

64theirhandsupandstarttosweatYouinchbackwardtothe

dooropen

65itandthencarefullyplacethebombonthefloorpointing

your

66blasteratitYouthenjumpbackthroughthedoorpunchthe

close

67buttonandblastthelocksotheGothonscantgetoutNow

thatthe

68bombisplacedyouruntotheescapepodtogetoffthistin

can

69

70Yourushthroughtheshipdesperatelytryingtomakeittothe

escape

71podbeforethewholeshipexplodesItseemslikehardlyany

Gothons

72areontheshipsoyourrunisclearofinterferenceYou

gettothe

73chamberwiththeescapepodsandnowneedtopickoneto

takeSomeof

74themcouldbedamagedbutyoudonthavetimeto

lookTheres5pods

75whichonedoyoutake

76)

77

78

79the_end_winner=Room(TheEnd

80

81Youjumpintopod2andhittheejectbuttonThepodeasily

slidesout

82intospaceheadingtotheplanetbelowAsitfliestothe

planetyou

83lookbackandseeyourshipimplodethenexplodelikeabright

star

84takingouttheGothonshipatthesametimeYouwon

85)

86

87

88the_end_loser=Room(TheEnd

89

90YoujumpintoarandompodandhittheejectbuttonThepod

escapes

91outintothevoidofspacethenimplodesasthehull

rupturescrushing

92yourbodyintojamjelly

93

94)

95

96escape_podadd_paths(

972the_end_winner

98the_end_loser

99)

100

101generic_death=Room(deathYoudied)

102

103the_bridgeadd_paths(

104throwthebombgeneric_death

105slowlyplacethebombescape_pod

106)

107

108laser_weapon_armoryadd_paths(

1090132the_bridge

110generic_death

111)

112

113central_corridoradd_paths(

114shootgeneric_death

115dodgegeneric_death

116tellajokelaser_weapon_armory

117)

118

119START=central_corridor

120

121defload_room(name)

122

123Thereisapotentialsecurityproblemhere

124WhogetstosetnameCanthatexposeavariable

125

126returnglobals()get(name)

127

128defname_room(room)

129

130SamepossiblesecurityproblemCanyoutrustroom

131Whatsabettersolutionthanthisglobalslookup

132

133forkeyvalueinglobals()items()

134ifvalue==room

135returnkeyYoursquollnoticethatthereareacouple

ofproblemswithourRoomclassandthismap1Wehavetoputthe

textthatwasintheif-elseclausesthatgotprintedbeforeentering

aroomaspartofeachroomThismeansyoucanrsquotshufflethe

planispherearoundwhichwouldbeniceYoursquollbefixingthatupin

thisexercise

2TherearepartsintheoriginalgamewherewerancodethatdeterminedthingslikethebombrsquoskeypadcodeortherightpodInthisgamewejustpicksomedefaultsandgowithitbutlateryoursquollbegivenStudyDrillstomakethisworkagain

3Irsquovejustmadeageneric_deathendingforallofthebaddecisionswhichyoursquollhavetofinishformeYoursquollneedtogobackthroughandaddinalltheoriginalendingsandmakesuretheywork

4Irsquovegotanewkindoftransitionlabeledthatwillbeusedforaldquocatch-allrdquoactionintheengine

Onceyoursquovegotthatbasicallywrittenoutherersquosthenewautomatedtesttestsplanisphere_testpythatyoushouldhavetogetyourselfstartedClickheretoviewcodeimage

planisphere_testspy

1fromnosetoolsimport

2fromgothonwebplanisphereimport

3

4deftest_room()

5gold=Room(GoldRoom

6Thisroomhasgoldinityoucangrab

Theresa

7doortothenorth)

8assert_equal(goldnameGoldRoom)

9assert_equal(goldpaths)

10

11deftest_room_paths()

12center=Room(CenterTestroominthecenter)

13north=Room(NorthTestroominthenorth)

14south=Room(SouthTestroominthesouth)

15

16centeradd_paths(northnorthsouthsouth)

17assert_equal(centergo(north)north)

18assert_equal(centergo(south)south)

19

20deftest_map()

21start=Room(StartYoucangowestanddownahole)

22west=Room(TreesTherearetreeshereyoucango

east)

23down=Room(DungeonItsdarkdownhereyoucango

up)

24

25startadd_paths(westwestdowndown)

26westadd_paths(eaststart)

27downadd_paths(upstart)

28

29assert_equal(startgo(west)west)

30assert_equal(startgo(west)go(east)start)

31assert_equal(startgo(down)go(up)start)

32

33deftest_gothon_game_map()

34start_room=load_room(START)

35assert_equal(start_roomgo(shoot)generic_death)

36assert_equal(start_roomgo(dodge)generic_death)

37

38room=start_roomgo(tellajoke)

39assert_equal(roomlaser_weapon_armory)Yourtaskinthis

partoftheexerciseistocompletethemapandmaketheautomated

testcompletelyvalidatethewholemapThisincludesfixingallthe

generic_deathobjectstoberealendingsMakesurethisworksreally

wellandthatyourtestisascompleteaspossiblebecausewersquollbe

changingthismaplaterandyoursquollusetheteststomakesureit

keepsworking

CreatinganEngineYoushouldhaveyourgamemapworkingandagoodunittestforitInowwantyoutomakeasimplelittlegameenginethatwillruntheroomscollectinputfromtheplayerandkeeptrackofwhereaplayerisinthegameWersquollbeusingthesessionsyoujustlearnedtomakeasimplegameenginethatwilldothefollowing

1Startanewgamefornewusers2Presenttheroomtotheuser3Takeinputfromtheuser4Runuserinputthroughthegame5Displaytheresultsandkeepgoinguntiltheuserdies

Todothisyoursquoregoingtotakethetrustyapppyyoursquovebeenhackingonandcreateafullyworkingsession-basedgameengineThecatchisIrsquomgoingtomakeaverysimpleonewithbasicHTMLfilesanditrsquollbeuptoyoutocompleteitHerersquosthebaseengineClickheretoviewcodeimage

apppy

1fromflaskimportFlasksessionredirecturl_forescape

request

2fromflaskimportrender_template

3fromgothonwebimportplanisphere

4

5app=Flask(__name__)

6

7approute()

8defindex()

9thisisusedtosetupthesessionwithstartingvalues

10session[room_name]=planisphereSTART

11returnredirect(url_for(game))

12

13approute(gamemethods=[GETPOST])

14defgame()

15room_name=sessionget(room_name)

16

17ifrequestmethod==GET

18ifroom_name

19room=planisphereload_room(room_name)

20returnrender_template(show_roomhtmlroom=room)

21else

22whyisthereheredoyouneedit

23returnrender_template(you_diedhtml)

24else

25action=requestformget(action)

26

27ifroom_nameandaction

28room=planisphereload_room(room_name)

29next_room=roomgo(action)

30

31ifnotnext_room

32session[room_name]=

planispherename_room(room)

33else

34session[room_name]=

planispherename_room(next_room)

35

36returnredirect(url_for(game))

37

38

39YOUSHOULDCHANGETHISIFYOUPUTONTHEINTERNET

40appsecret_key=A0Zr98j3yXR~XHHjmN]LWXRT

41

42if__name__==__main__

43apprun()Thereareevenmorenewthingsinthisscript

butamazinglyitrsquosanentireweb-basedgameengineinasmallfile

BeforeyourunapppyyouneedtochangeyourPYTHONPATHenvironment

variableDonrsquotknowwhatthatisIknowitrsquoskindofdumbbutyou

havetolearnwhatthisistorunevenbasicPythonprogramsthatrsquos

howPythonpeoplelikethings

InyourTerminaltypeClickheretoviewcodeimageexportPYTHONPATH=$PYTHONPATH

OnWindowsPowerShelldoClickheretoviewcodeimage$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

YoushouldonlyhavetodoitoncepershellsessionbutifyougetanimporterrorthenyouprobablyneedtodothisoryoudiditwrongYoushouldnextdeletetemplateshello_formhtmlandtemplatesindexhtmlandcreatethetwotemplatesmentionedintheprecedingcodeHerersquosaverysimpletemplatesshow_roomhtmlClickheretoviewcodeimage

show_roomhtml

extendslayouthtml

blockcontent

lth1gtroomnamelth1gt

ltpregt

roomdescription

ltpregt

ifroomnamein[deathTheEnd]

ltpgtltahref=gtPlayAgainltagtltpgt

else

ltpgt

ltformaction=gamemethod=POSTgt

-ltinputtype=textname=actiongtltinputtype=SUBMITgt

ltformgt

ltpgt

endif

endblock

ThatisthetemplatetoshowaroomasyoutravelthroughthegameNextyouneedonetotellsomeonetheydiedinthecasethattheygottotheendofthemaponaccidentwhichistemplatesyou_diedhtmlClickheretoviewcodeimage

you_diedhtml

lth1gtYouDiedlth1gt

ltpgtLookslikeyoubitthedustltpgt

ltpgtltahref=gtPlayAgainltagtltpgtWiththoseinplaceyoushouldnow

beabletodothefollowing1Getthetesttestsapp_testspy

workingagainsothatyouaretestingthegameYouwonrsquotbeableto

domuchmorethanafewclicksinthegamebecauseofsessionsbut

youshouldbeabletodosomebasics

2Runthepython36apppyscriptandtestoutthegameYoushouldbeabletorefreshandfixthegamelikenormalYoushouldalsobeabletoworkwiththegameHTMLandengineuntilitdoesallthethingsyouwantittodo

YourFinalExamDoyoufeellikethiswasahugeamountofinformationthrownatyouallatonceGoodIwantyoutohavesomethingtotinkerwithwhileyoubuildyourskillsTocompletethisexerciseIrsquomgoingtogiveyouafinalsetoftasksforyoutocompleteonyourownYoursquollnoticethatwhatyoursquovewrittensofarisnrsquotverywellbuiltitisjustafirstversionofthecodeYourjobnowistomakethegamemorecompletebydoingthesethings

1FixallthebugsImentioninthecodeandanythatIdidnrsquotmentionIfyoufindnewbugsletmeknow

2Improvealloftheautomatedtestssothatyoutestmoreoftheapplicationandgettoapointwhereyouuseatestratherthanyourbrowsertochecktheapplicationwhileyouwork

3MaketheHTMLlookbetter4Researchloginsandcreateasignupsystemfortheapplicationsopeoplecanhaveloginsandhighscores

5Completethegamemapmakingitaslargeandfeature-completeaspossible

6Givepeoplealdquohelprdquosystemthatletsthemaskwhattheycandoateachroominthegame

7Addanyotherfeaturesyoucanthinkoftothegame8CreateseveralldquomapsrdquoandletpeoplechooseagametheywanttorunYourapppyengineshouldbeabletorunanymapofroomsyougiveitsoyoucansupportmultiplegames

9FinallyusewhatyoulearnedinExercises48and49tocreateabetterinputprocessorYouhavemostofthecodenecessaryyoujustneedtoimprovethegrammarandhookituptoyourinputformandtheGameEngine

Goodluck

Goodluck

CommonStudentQuestionsIrsquomusingsessionsinmygameandIcanrsquottestitwithnosetestsReadtheFlaskTestingDocumentationaboutldquoOtherTestingTricksrdquo(httpflaskpocooorgdocs012testingother-testing-tricks)forinformationoncreatingfakesessionsinsideyourtests

IgetanImportErrorItcouldbeoneormoreofthesewrongdirectorywrongPythonversionPYTHONPATHnotsetno__init__pyfileandorspellingmistakeinimport

NextSteps

YoursquorenotaprogrammerquiteyetIliketothinkofthisbookasgivingyouyourldquoprogrammingblackbeltrdquoYouknowenoughtostartanotherbookonprogrammingandhandleitjustfineThisbookshouldhavegivenyouthementaltoolsandattitudeyouneedtogothroughmostPythonbooksandactuallylearnsomethingItmightevenmakeiteasyIrecommendyoucheckoutsomeoftheseprojectsandtrytobuildsomethingwiththem

bullLearnRubyTheHardWay(httpslearnrubythehardwayorg)YouwilllearnevenmoreaboutprogrammingasyoulearnmoreprogramminglanguagessotrylearningRubytoo

bullTheDjangoTutorial(httpsdocsdjangoprojectcomen111intro)BuildawebapplicationwiththeDjangowebframework

bullSciPy(httpswwwscipyorg)Checkthisoutifyoursquoreintosciencemathandengineering

bullPyGame(httpwwwpygameorg)MakeagamewithgraphicsandsoundbullPandas(httppandaspydataorg)Usethisfordoingdatamanipulationandanalysis

bullNaturalLanguageToolkit(httpwwwnltkorg)Usethisforanalyzingwrittentextandwritingthingslikespamfiltersandchatbots

bullTensorFlow(httpswwwtensorfloworg)Usethisformachinelearningandvisualization

bullRequests(httpdocspython-requestsorg)LearntheclientsideofHTTPandtheweb

bullScraPy(httpsscrapyorg)Tryscrapingsomewebsitestogetinformationoffthem

bullKivy(httpskivyorg)Createuserinterfacesondesktopsandmobileplatforms

bullLearnCTheHardWay(httpslearncodethehardwayorg)AfteryoursquorefamiliarwithPythontrylearningCandalgorithmswithmyotherbookTakeitslowCisdifferentbutaverygoodthingtolearn

PickoneoftheprecedingresourcesandgothroughanytutorialsanddocumentationtheyhaveAsyougothroughdocumentationwithcodeinittype

inallofthecodeandmakeitworkThatrsquoshowIdoitThatrsquoshoweveryprogrammerdoesitReadingprogrammingdocumentationisnotenoughtolearnityouhavetodoitAfteryougetthroughthetutorialandanyotherdocumentationtheyhavemakesomethingAnythingwilldoevensomethingsomeoneelsehasalreadywrittenJustmakesomethingJustunderstandanythingyouwritewillprobablysuckThatrsquosalrightthoughIsuckateveryprogramminglanguageatfirstNobodywritespureperfectgoldwhentheyrsquoreabeginnerandanyonewhotellsyoutheydidisahugeliar

HowtoLearnAnyProgrammingLanguageIrsquomgoingtoteachyouhowtolearnmostoftheprogramminglanguagesyoumaywanttolearninthefutureTheorganizationofthisbookisbasedonhowIandmanyotherprogrammerslearnnewlanguagesTheprocessthatIusuallyfollowisasfollows

1Getabookorsomeintroductorytextaboutthelanguage2Gothroughthebookandtypeinallofthecodemakingallofitrun3Readthebookasyouworkonthecodetakingnotes4Usethelanguagetoimplementasmallsetofprogramsyouarefamiliarwithinanotherlanguage

5ReadotherpeoplersquoscodeinthelanguageandtrytocopytheirpatternsInthisbookIforcedyoutogothroughthisprocessveryslowlyandinsmallchunksOtherbooksarenrsquotorganizedthesamewayandthismeansyouhavetoextrapolatehowIrsquovemadeyoudothistohowtheircontentisorganizedThebestwaytodothisistoreadthebooklightlyandmakealistofallthemajorcodesectionsTurnthislistintoasetofexercisesbasedonthechaptersandthensimplydotheminorderoneatatimeTheprecedingprocessalsoworksfornewtechnologiesassumingtheyhavebooksyoucanreadForanythingwithoutbooksyoudotheaboveprocessbutuseonlinedocumentationorsourcecodeasyourinitialintroductionEachnewlanguageyoulearnmakesyouabetterprogrammerandasyoulearnmorelanguagestheybecomeeasiertolearnByyourthirdorfourthlanguageyoushouldbeabletopickupsimilarlanguagesinaweekwithstrangerlanguagestakinglongerNowthatyouknowPythonyoucouldpotentiallylearnRubyandJavaScriptfairlyquicklybycomparisonThisissimplybecausemanylanguagessharesimilarconceptsandonceyoulearntheconceptsinonelanguagetheyworkinothersThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbea

ThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbeastupidtouristAstupidtouristissomeonewhogoestoanothercountryandthencomplainsthatthefoodisnrsquotlikethefoodathome(ldquoWhycanrsquotIgetagoodburgerinthisstupidcountryrdquo)WhenyoursquorelearninganewlanguageassumethatwhatitdoesisnrsquotstupiditrsquosjustdifferentandembraceitsoyoucanlearnitAfteryoulearnalanguagethoughdonrsquotbeaslavetothatlanguagersquoswayofdoingthingsSometimesthepeoplewhousealanguageactuallydosomeveryidioticthingsfornootherreasonthanldquothatrsquoshowwersquovealwaysdoneitrdquoIfyoulikeyourstylebetterandyouknowhoweveryoneelsedoesitthenfeelfreetobreaktheirrulesifitimprovesthingsIreallyenjoylearningnewprogramminglanguagesIthinkofmyselfasaldquoprogrammeranthropologistrdquoandthinkoflanguagesaslittleinsightsaboutthegroupofprogrammerswhousethemIrsquomlearningalanguagetheyallusetotalktoeachotherthroughcomputersandIfindthisfascinatingThenagainIrsquomkindofaweirdguysojustlearnprogramminglanguagesbecauseyouwanttoEnjoyThisisreallyfunstuff

AdvicefromanOldProgrammer

YoursquovefinishedthisbookandhavedecidedtocontinuewithprogrammingMaybeitwillbeacareerforyouormaybeitwillbeahobbyYoursquollneedsomeadvicetomakesureyoucontinueontherightpathandgetthemostenjoymentoutofyournewlychosenactivityIrsquovebeenprogrammingforaverylongtimeSolongthatitrsquosincrediblyboringtomeAtthetimethatIwrotethisbookIknewabout20programminglanguagesandcouldlearnnewonesinaboutadaytoaweekdependingonhowweirdtheywereEventuallythoughthisjustbecameboringandcouldnrsquotholdmyinterestanymoreThisdoesnrsquotmeanIthinkprogrammingisboringorthatyouwillthinkitrsquosboringonlythatIfindituninterestingatthispointinmyjourneyWhatIdiscoveredafterthisjourneyoflearningisthatitrsquosnotthelanguagesthatmatterbutwhatyoudowiththemActuallyIalwaysknewthatbutIrsquodgetdistractedbythelanguagesandforgetitperiodicallyNowIneverforgetitandneithershouldyouWhichprogramminglanguageyoulearnandusedoesnrsquotmatterDonotgetsuckedintothereligionsurroundingprogramminglanguagesasthatwillonlyblindyoutotheirtruepurposeofbeingyourtoolfordoinginterestingthingsProgrammingasanintellectualactivityistheonlyartformthatallowsyoutocreateinteractiveartYoucancreateprojectsthatotherpeoplecanplaywithandyoucantalktothemindirectlyNootherartformisquitethisinteractiveMoviesflowtotheaudienceinonedirectionPaintingsdonotmoveCodegoesbothwaysProgrammingasaprofessionisonlymoderatelyinterestingItcanbeagoodjobbutyoucouldmakeaboutthesamemoneyandbehappierrunningafastfoodjointYoursquoremuchbetteroffusingcodeasyoursecretweaponinanotherprofessionPeoplewhocancodeintheworldoftechnologycompaniesareadimeadozenandgetnorespectPeoplewhocancodeinbiologymedicinegovernmentsociologyphysicshistoryandmathematicsarerespectedandcandoamazingthingstoadvancethosedisciplinesOfcourseallofthisadviceispointlessIfyoulikedlearningtowritesoftwarewiththisbookyoushouldtrytouseittoimproveyourlifeanywayyoucanGooutandexplorethisweirdwonderfulnewintellectualpursuitthatbarelyanyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhile

anyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhileyoucanFinallyIrsquollsaythatlearningtocreatesoftwarechangesyouandmakesyoudifferentNotbetterorworsejustdifferentYoumayfindthatpeopletreatyouharshlybecauseyoucancreatesoftwaremaybeusingwordslikeldquonerdrdquoMaybeyoursquollfindthatbecauseyoucandissecttheirlogictheyhatearguingwithyouYoumayevenfindthatsimplyknowinghowacomputerworksmakesyouannoyingandweirdtothemTothisIhavejustonepieceofadvicetheycangotohellTheworldneedsmoreweirdpeoplewhoknowhowthingsworkandwholovetofigureitalloutWhentheytreatyoulikethisjustrememberthatthisisyourjourneynottheirsBeingdifferentisnotacrimeandpeoplewhotellyouitisarejustjealousthatyoursquovepickedupaskilltheyneverintheirwildestdreamscouldacquireYoucancodeTheycannotThatisprettydamncool

AppendixCommandLineCrashCourse

ThisappendixisasuperfastcourseinusingthecommandlineItisintendedtobedonerapidlyinaboutadayortwoandnotmeanttoteachyouadvancedshellusage

IntroductionShutUpandShellThisappendixisacrashcourseinusingthecommandlinetomakeyourcomputerperformtasksAsacrashcourseitrsquosnotasdetailedorextensiveasmyotherbooksItissimplydesignedtogetyoubarelycapableenoughtostartusingyourcomputerlikearealprogrammerdoesWhenyoursquoredonewiththisappendixyouwillbeabletogivemostofthebasiccommandsthateveryshellusertoucheseverydayYoursquollunderstandthebasicsofdirectoriesandafewotherconceptsTheonlypieceofadviceIamgoingtogiveyouisthis

ShutupandtypeallofthisinSorrytobemeanbutthatrsquoswhatyouhavetodoIfyouhaveanirrationalfearofthecommandlinetheonlywaytoconqueranirrationalfearistojustshutupandfightthroughitYouarenotgoingtodestroyyourcomputerYouarenotgoingtobethrownintosomejailatthebottomofMicrosoftrsquosRedmondcampusYourfriendswonrsquotlaughatyouforbeinganerdSimplyignoreanystupidweirdreasonsyouhaveforfearingthecommandlineWhyBecauseifyouwanttolearntocodethenyoumustlearnthisProgramminglanguagesareadvancedwaystocontrolyourcomputerwithlanguageThecommandlineisthebabybrotherofprogramminglanguagesLearningthecommandlineteachesyoutocontrolthecomputerusinglanguageOnceyougetpastthatyoucanthenmoveontowritingcodeandfeelinglikeyouactuallyownthehunkofmetalyoujustbought

HowtoUseThisAppendixThebestwaytousethisappendixistodothefollowing

bullGetyourselfasmallpapernotebookandapenbullStartatthebeginningoftheappendixanddoeachexerciseexactlyasyoursquoretold

bullWhenyoureadsomethingthatdoesnrsquotmakesenseorthatyoudonrsquotunderstandwriteitdowninyournotebookLeavealittlespacesoyoucanwriteananswer

bullAfteryoufinishanexercisegobackthroughyournotebookandreviewthequestionsyouhaveTrytoanswerthembysearchingonlineandaskingfriendswhomightknowtheanswerEmailmeathelplearncodethehardwayorgandIrsquollhelpyoutoo

JustkeepgoingthroughthisprocessofdoinganexercisewritingdownquestionsyouhavethengoingbackthroughandansweringthequestionsyoucanBythetimeyoursquoredoneyoursquollactuallyknowalotmorethanyouthinkaboutusingthecommandline

YouWillBeMemorizingThingsIrsquomwarningyouaheadoftimethatIrsquomgoingtomakeyoumemorizethingsrightawayThisisthequickestwaytogetyoucapableatsomethingbutforsomepeoplememorizationispainfulJustfightthroughitanddoitanywayMemorizationisanimportantskillinlearningthingssoyoushouldgetoveryourfearofitHerersquoshowyoumemorizethings

bullTellyourselfyouwilldoitDonrsquottrytofindtricksoreasywaysoutofitjustsitdownanddoit

bullWritewhatyouwanttomemorizeonsomeindexcardsPutonehalfofwhatyouneedtolearnononesidethenanotherhalfontheotherside

bullEverydayforabout15to30minutesdrillyourselfontheindexcardstryingtorecalleachonePutanycardsyoudonrsquotgetrightintoadifferentpilejustdrillthosecardsuntilyougetboredthentrythewholedeckandseeifyouimprove

bullBeforeyougotobeddrilljustthecardsyougotwrongforabout5minutesthengotosleep

ThereareothertechniqueslikeyoucanwritewhatyouneedtolearnonasheetofpaperlaminateitthenstickittothewallofyourshowerWhileyoursquorebathingdrilltheknowledgewithoutlookingandwhenyougetstuckglanceatittorefreshyourmemoryIfyoudothiseverydayyoushouldbeabletomemorizemostthingsItellyoutomemorizeinaboutaweektoamonthOnceyoudonearlyeverythingelsebecomeseasierandintuitivewhichisthepurposeofmemorizationItrsquosnottoteachyouabstractconceptsbutrathertoingrainthebasicssothattheyareintuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthese

intuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthesebasicstheystopbeingspeedbumpspreventingyoufromlearningmoreadvancedabstractconcepts

TheSetupInthisappendixyouwillbeinstructedtodothreethings

bullDosomethingsinyourshell(commandlineTerminalPowerShell)bullLearnaboutwhatyoujustdidbullDomoreonyourown

ForthisfirstexerciseyoursquollbeexpectedtogetyourTerminalopenandworkingsothatyoucandotherestoftheappendix

DoThisGetyourTerminalshellorPowerShellworkingsoyoucanaccessitquicklyandknowthatitworksmacOS

FormacOSyoursquollneedtodothisbullHolddownthecommandkeyandhitthespacebarbullAsearchbarwillpopupbullTypeTerminalbullClickontheTerminalapplicationthatlookskindoflikeablackboxbullThiswillopenTerminalbullYoucannowgotoyourdockandCTRL-clicktopullupthemenuthenselectOptionsrarrKeepIndock

NowyouhaveyourTerminalopenanditrsquosinyourdocksoyoucangettoitLinux

IrsquomassumingthatifyouhaveLinuxthenyoualreadyknowhowtogetatyourTerminalLookthroughthemenuforyourwindowmanagerforanythingnamedldquoShellrdquoorldquoTerminalrdquoWindows

OnWindowswersquoregoingtousePowerShellPeopleusedtoworkwithaprogramcalledcmdexebutitrsquosnotnearlyasusableasPowerShellIfyouhaveWindows7orlaterdothis

bullClickStartbullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquo

bullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquobullHitEnter

IfyoudonrsquothaveWindows7youshouldseriouslyconsiderupgradingIfyoustillinsistonnotupgradingthenyoucantryinstallingPowerShellfromMicrosoftrsquosdownloadcenterSearchonlinetofindldquopowershelldownloadsrdquoforyourversionofWindowsYouareonyourownthoughsinceIdonrsquothaveWindowsXPbuthopefullythePowerShellexperienceisthesame

YouLearnedThisYoulearnedhowtogetyourTerminalopensoyoucandotherestofthisappendix

WarningIfyouhavethatreallysmartfriendwhoalreadyknowsLinuxignoreherwhenshetellsyoutousesomethingotherthanBashIrsquomteachingyouBashThatrsquositShewillclaimthatzshwillgiveyou30moreIQpointsandwinyoumillionsinthestockmarketIgnoreherYourgoalistogetcapableenoughandatthislevelitdoesnrsquotmatterwhichshellyouuseThenextwarningisstayoffIRCorotherplaceswhereldquohackersrdquohangoutTheythinkitrsquosfunnytohandyoucommandsthatcandestroyyourcomputerThecommandrm-rfisaclassicthatyoumustnevertypeJustavoidthemIfyouneedhelpmakesureyougetitfromsomeoneyoutrustandnotfromrandomidiotsontheinternet

DoMoreThisexercisehasalargeldquodomorerdquopartTheotherexercisesarenotasinvolvedasthisonebutIrsquomhavingyouprimeyourbrainfortherestoftheappendixbydoingsomememorizationJusttrustmethiswillmakethingssilkysmoothlateronLinuxmacOS

TakethislistofcommandsandcreateindexcardswiththenamesontheleftononesideandthedefinitionsontheothersideDrillthemeverydaywhilecontinuingwiththelessonsinthisappendix

pwdprintworkingdirectoryhostnamemycomputerrsquosnetworkname

mkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectorymvmoveafileordirectorylesspagethroughafilecatprintthewholefilexargsexecuteargumentsfindfindfilesgrepfindthingsinsidefilesmanreadamanualpageaproposfindwhichmanualpageisappropriateenvlookatyourenvironmentechoprintsomeargumentsexportexportsetanewenvironmentvariableexitexittheshellsudoDANGERbecomesuperuserrootDANGER

Windows

IfyoursquoreusingWindowsthenherersquosyourlistofcommandspwdprintworkingdirectoryhostnamemycomputerrsquosnetworknamemkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectory

robocopyrobustcopymvmoveafileordirectorymorepagethroughafiletypeprintthewholefileforfilesrunacommandonlotsoffilesdir-rfindfilesselect-stringfindthingsinsidefileshelpreadamanualpagehelpctrfindwhatmanualpageisappropriateechoprintsomeargumentssetexportsetanewenvironmentvariableexitexittheshellrunasDANGERbecomesuperuserrootDANGER

DrilldrilldrillDrilluntilyoucansaythesephrasesrightawaywhenyouseethatwordThendrilltheinversesothatyoureadthephraseandknowwhatcommandwilldothatYoursquorebuildingyourvocabularybydoingthisbutdonrsquotspendsomuchtimeyougonutsandgetbored

PathsFoldersDirectories(pwd)Inthisexerciseyoulearnhowtoprintyourworkingdirectorywiththepwdcommand

DoThisIrsquomgoingtoteachyouhowtoreadtheseldquosessionsrdquothatIshowyouYoudonrsquothavetotypeeverythingIlistherejustsomeoftheparts

bullYoudonottypeinthe$(Unix)orlt(Windows)ThatrsquosjustmeshowingyoumysessionsoyoucanseewhatIgot

bullYoutypeinthestuffafter$orltthenhitEnterSoifIhave$pwdyoutypejustpwdandhitEnter

bullYoucanthenseewhatIhaveforoutputfollowedbyanother$orltpromptThatcontentistheoutputandyoushouldseethesameoutput

LetrsquosdoasimplefirstcommandsoyoucangetthehangofthisLinuxmacOS

Exercise2Session

$pwd

Userszedshaw

$

Windows

Exercise2WindowsSession

PSCUserszedgtpwd

Path

----

CUserszed

PSCUserszedlt

WarningInthisappendixIneedtosavespacesothatyoucanfocusontheimportantdetailsofthecommandsTodothisIrsquomgoingtostripoutthefirstpartoftheprompt(thePSCUserszedabove)andleavejustthelittlegtpartThismeansyourpromptwonrsquotlookexactlythesamebutdonrsquotworryaboutthatRememberthatfromnowonIrsquollonlyhavethegttotellyouthatrsquosthepromptIrsquomdoingthesamethingfortheUnixpromptsbutUnixpromptsaresovariedthatmostpeoplegetusedto$meaningldquojustthepromptrdquo

YouLearnedThisYourpromptwilllookdifferentfrommineYoumayhaveyourusernamebeforethe$andthenameofyourcomputerOnWindowsitwillprobablylookdifferenttooThekeyisthatyouseethefollowingpattern

bullTherersquosapromptbullYoutypeacommandthereInthiscaseitrsquospwdbullItprintedsomethingbullRepeat

Youjustlearnedwhatpwddoeswhichmeansldquoprintworkingdirectoryrdquo

WhatrsquosadirectoryItrsquosafolderFolderanddirectoryarethesamethingandtheyrsquoreusedinterchangeablyWhenyouopenyourfilebrowseronyourcomputertographicallyfindfilesyouarewalkingthroughfoldersThosefoldersaretheexactsamethingsastheseldquodirectoriesrdquowersquoregoingtoworkwith

DoMorebullTypepwd20timesandeachtimesayldquoprintworkingdirectoryrdquobullWritedownthepaththatthiscommandgivesyouFinditwithyourgraphicalfilebrowserofchoice

bullNoseriouslytypeit20timesandsayitoutloudSsshJustdoit

IfYouGetLostAsyougothroughtheseinstructionsyoumaygetlostYoumaynotknowwhereyouareorwhereafileisandhavenoideahowtocontinueTosolvethisproblemIamgoingtoteachyouthecommandstotypetostopbeinglostWheneveryougetlostitismostlikelybecauseyouweretypingcommandsandhavenoideawhereyoursquoveendedupWhatyoushoulddoistypepwdtoprintyourcurrentdirectoryThistellsyouwhereyouareThenextthingisyouneedtohaveawayofgettingbacktowhereyouaresafeyourhomeTodothistypecd~andyouarebackinyourhomeThismeansifyougetlostatanytimetype

pwd

cd~

ThefirstcommandpwdtellsyouwhereyouareThesecondcommandcd~takesyouhomesoyoucantryagain

DoThisRightnowfigureoutwhereyouareandthengohomeusingpwdandcd~Thiswillmakesureyouarealwaysintherightplace

YouLearnedThisHowtogetbacktoyourhomeifyouevergetlost

MakeaDirectory(mkdir)Inthisexerciseyoulearnhowtomakeanewdirectory(folder)usingthemkdircommand

DoThis

DoThisRememberYouneedtogohomefirstDoyourpwdthencd~beforedoingthisexerciseBeforeyoudoallexercisesinthisappendixalwaysgohomefirstLinuxmacOS

Clickheretoviewcodeimage

Exercise4Session

$pwd

$cd~

$mkdirtemp

$mkdirtempstuff

$mkdirtempstuffthings

$mkdir-ptempstuffthingsorangeapplepeargrape

$

Windows

Clickheretoviewcodeimage

Exercise4WindowsSession

gtpwd

gtcd~

gtmkdirtemp

DirectoryCUserszed

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMtemp

gtmkdirtempstuff

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMstuff

gtmkdirtempstuffthings

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtmkdirtempstuffthingsorangeapplepeargrape

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gt

ThisistheonlytimeIrsquolllistthepwdandcd~commandsTheyareexpectedintheexerciseseverytimeDothemallthetime

YouLearnedThisNowwegetintotypingmorethanonecommandTheseareallthedifferentwaysyoucanrunmkdirWhatdoesmkdirdoItmakesdirectoriesWhyareyouaskingthatYoushouldbedoingyourindexcardsandgettingyourcommandsmemorizedIfyoudonrsquotknowthatldquomkdirmakesdirectoriesrdquothenkeepworkingtheindexcardsWhatdoesitmeantomakeadirectoryYoumightcalldirectoriesldquofoldersrdquoTheyrsquorethesamethingAllyoudidaboveiscreatedirectoriesinsidedirectoriesinsideofmoredirectoriesThisiscalledaldquopathrdquoanditrsquosawayofsayingldquofirsttempthenstuffthenthingsandthatrsquoswhereIwantitrdquoItrsquosasetofdirectionstothecomputerofwhereyouwanttoputsomethinginthetreeoffolders(directories)thatmakeupyourcomputerrsquosharddisk

WarningInthisappendixIrsquomusingthe(slash)characterforallpathssincetheyworkthesameonallcomputersnowHoweverWindowsuserswillneedtoknowthatyoucanalsousethe(backslash)characterandotherWindowsuserswilltypicallyexpectthatattimes

DoMorebullTheconceptofaldquopathrdquomightconfuseyouatthispointDonrsquotworryWersquolldoalotmorewiththemandthenyoursquollgetit

bullMake20otherdirectoriesinsidethetempdirectoryinvariouslevelsGolookatthemwithagraphicalfilebrowser

bullMakeadirectorywithaspaceinthenamebyputtingquotesarounditmkdirIHaveFun

bullIfthetempdirectoryalreadyexiststhenyoursquollgetanerrorUsecdtochangetoaworkdirectorythatyoucancontrolandtryitthereOnWindowsDesktopisagoodplace

ChangeDirectory(cd)Inthisexerciseyoulearnhowtochangefromonedirectorytoanotherusingthecdcommand

DoThisIrsquomgoingtogiveyoutheinstructionsforthesesessionsonemoretime

bullYoudonottypeinthe$(Unix)orgt(Windows)bullYoutypeinthestuffafterthisthenhitEnterIfIhave$cdtempyoujusttypecdtempandhitEnter

bullTheoutputcomesafteryouhitEnterfollowedbyanother$orgtpromptbullAlwaysgohomefirstDopwdandthencd~soyougobacktoyourstartingpoint

LinuxmacOS

Clickheretoviewcodeimage

Exercise5Session

$cdtemp

$pwd

~temp

$cdstuff

$pwd

~tempstuff

$cdthings

$pwd

~tempstuffthings

$cdorange

$pwd

~tempstuffthingsorange

$cdapple

$pwd

~tempstuffthingsorangeapple

$cdpear

$pwd

~tempstuffthingsorangeapplepear

$cdgrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$cd

$pwd

~tempstuffthingsorangeapple

$cd

$cd

$pwd

~tempstuffthings

$cd

$pwd

~

$cdtempstuffthingsorangeapplepeargrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$pwd

~

$

Windows

Clickheretoviewcodeimage

Exercise5WindowsSession

gtcdtemp

gtpwd

Path

----

CUserszedtemp

gtcdstuff

gtpwd

Path

----

CUserszedtempstuff

gtcdthings

gtpwd

Path

----

CUserszedtempstuffthings

gtcdorange

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcdapple

gtpwd

Path

----

CUserszedtempstuffthingsorangeapple

gtcdpear

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepear

gtcdgrape

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepeargrape

gtcd

gtcd

gtcd

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcd

gtpwd

Path

----

CUserszedtempstuff

gtcd

gtcd

gtcdtempstuffthingsorangeapplepeargrape

gtcd

gtpwd

Path

----

CUserszed

gt

YouLearnedThisYoumadeallthesedirectoriesinthelastexerciseandnowyoursquorejustmovingaroundinsidethemwiththecdcommandInmysessionaboveIalsousepwdtocheckwhereIamsoremembernottotypetheoutputthatpwdprintsForexampleonline3yousee~tempbutthatrsquostheoutputofpwdfromthepromptaboveitDonottypethisinYoushouldalsoseehowIusethetomoveldquouprdquointhetreeandpath

DoMoreAveryimportantpartoflearningtousethecommandlineinterface(CLI)onacomputerwithagraphicaluserinterface(GUI)isfiguringouthowtheyworktogetherWhenIstartedusingcomputerstherewasnoGUIandyoudideverythingwiththeDOSprompt(theCLI)LaterwhencomputersbecamepowerfulenoughthateveryonecouldhavegraphicsitwassimpleformetomatchCLIdirectorieswithGUIwindowsandfoldersMostpeopletodayhoweverhavenocomprehensionoftheCLIpathsanddirectoriesInfactitrsquosverydifficulttoteachittothemandtheonlywaytolearnabouttheconnectionisforyoutoconstantlyworkwiththeCLIuntilonedayitclicksthatthingsyoudointheGUIwillshowupintheCLI

dayitclicksthatthingsyoudointheGUIwillshowupintheCLIThewayyoudothisisbyspendingsometimefindingdirectorieswithyourGUIfilebrowserthengoingtothemwithyourCLIThisiswhatyoursquolldonext

bullcdtotheappledirectorywithonecommandbullcdbacktotempwithonecommandbutnotfurtherabovethatbullFindouthowtocdtoyourldquohomedirectoryrdquowithonecommandbullcdtoyourDocumentsdirectorythenfinditwithyourGUIfilebrowser(FinderWindowsExploreretc)

bullcdtoyourDownloadsdirectorythenfinditwithyourfilebrowserbullFindanotherdirectorywithyourfilebrowserthencdtoitbullRememberwhenyouputquotesaroundadirectorywithspacesinitYoucandothatwithanycommandForexampleifyouhaveadirectoryIHaveFunthenyoucandocdIHaveFun

ListDirectory(ls)Inthisexerciseyoulearnhowtolistthecontentsofadirectorywiththelscommand

DoThisBeforeyoustartmakesureyoucdbacktothedirectoryabovetempIfyouhavenoideawhereyouareusepwdtofigureitoutandthenmovethereLinuxmacOS

Exercise6Session

$cdtemp

$ls

stuff

$cdstuff

$ls

things

$cdthings

$ls

orange

$cdorange

$ls

apple

$cdapple

$ls

pear

$cdpear

$ls

$cdgrape

$ls

$cd

$ls

grape

$cd

$ls

orange

$cd

$ls

stuff

$

Windows

Clickheretoviewcodeimage

Exercise6WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuff

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcdthings

gtls

DirectoryCUserszedtempstuffthings

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMorange

gtcdorange

gtls

DirectoryCUserszedtempstuffthingsorange

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMapple

gtcdapple

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcdpear

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcdgrape

gtls

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gt

YouLearnedThisThelscommandlistsoutthecontentsofthedirectoryyouarecurrentlyinYoucanseemeusecdtochangeintodifferentdirectoriesandthenlistwhatrsquosinthemsoIknowwhichdirectorytogotonextTherearealotofoptionsforthelscommandbutyoursquolllearnhowtogethelponthoselaterwhenwecoverthehelpcommand

DoMore

bullTypeeveryoneofthesecommandsinYouhavetoactuallytypethesetolearnthemJustreadingthemisnotgoodenoughIrsquollstopyellingnow

bullOnUnixtrythels-lRcommandwhileyoursquoreintempbullOnWindowsdothesamethingwithdir-RbullUsecdtogettootherdirectoriesonyourcomputerandthenuselstoseewhatrsquosinthem

bullUpdateyournotebookwithnewquestionsIknowyouprobablyhavesomebecauseIrsquomnotcoveringeverythingaboutthiscommand

bullRememberthatifyougetlostuselsandpwdtofigureoutwhereyouareandthengotowhereyouneedtobewithcd

RemoveDirectory(rmdir)Inthisexerciseyoulearnhowtoremoveanemptydirectory

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise7Session

$cdtemp

$ls

stuff

$cdstuffthingsorangeapplepeargrape

$cd

$rmdirgrape

$cd

$rmdirpear

$cd

$ls

apple

$rmdirapple

$cd

$ls

orange

$rmdirorange

$cd

$ls

things

$rmdirthings

$cd

$ls

stuff

$rmdirstuff

$pwd

~temp

$

WarningIfyoutrytodormdironmacOSanditrefusestoremovethedirectoryeventhoughyouarepositiveitrsquosemptythenthereisactuallyafileintherecalledDS_StoreInthatcasetyperm-rfltdirgtinstead(replaceltdirgtwiththedirectoryname)

Windows

Clickheretoviewcodeimage

Exercise7WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuffthingsorangeapplepeargrape

gtcd

gtrmdirgrape

gtcd

gtrmdirpear

gtcd

gtrmdirapple

gtcd

gtrmdirorange

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMthings

gtrmdirthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMstuff

gtrmdirstuff

gtpwd

Path

----

CUserszedtemp

gtcd

gt

YouLearnedThisIrsquomnowmixingupthecommandssomakesureyoutypethemexactlyandpayattentionEverytimeyoumakeamistakeitrsquosbecauseyouarenrsquotpayingattentionIfyoufindyourselfmakingmanymistakesthentakeabreakorjustquitforthedayYoursquovealwaysgottomorrowtotryagainInthisexampleyoursquolllearnhowtoremoveadirectoryItrsquoseasyYoujustgotothedirectoryrightaboveitthentypermdirltdirgtreplacingltdirgtwiththenameofthedirectorytoremove

DoMorebullMake20moredirectoriesandremovethemallbullMakeasinglepathofdirectoriesthatis10deepandremovethemoneatatimejustlikeIdidpreviously

bullIfyoutrytoremoveadirectorywithcontentsyouwillgetanerrorIrsquollshowyouhowtoremovethoseinlaterexercises

MovingAround(pushdpopd)InthisexerciseyoulearnhowtosaveyourcurrentlocationandgotoanewlocationwithpushdYouthenlearnhowtoreturntothesavedlocationwithpopd

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise8Session

$cdtemp

$mkdirilikeicecream

$pushdilikeicecream

~tempilikeicecream~temp

$popd

~temp

$pwd

~temp

$pushdilike

tempiliketemp

$pwd

~tempilike

$pushdicecream

~tempilikeicecreamtempiliketemp

$pwd

~tempilikeicecream

$popd

tempiliketemp

$pwd

~tempilike

$popd

~temp

$pushdilikeicecream

~tempilikeicecream~temp

$pushd

~temp~tempilikeicecream

$pwd

~temp

$pushd

~tempilikeicecream~temp

$pwd

~tempilikeicecream

$

Windows

Windows

Clickheretoviewcodeimage

Exercise8WindowsSession

gtcdtemp

gtmkdirilikeicecream

DirectoryCUserszedtempilike

ModeLastWriteTimeLengthName

---------------------------

d----122020111105AMicecream

gtpushdilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtemp

gtpushdilike

gtpwd

Path

----

CUserszedtempilike

gtpushdicecream

gtpwd

Path

----

CUserszedtempilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtempilike

gtpopd

gt

WarningInWindowsyounormallydonrsquotneedthe-poptionlikeyoudoinLinuxHoweverIbelievethisisamorerecentdevelopmentsoyoumayrunintoolderWindowsPowerShellversionsthatdorequirethe-pIfyouhavemoreinformationonthispleaseemailmeathelplearncodethehardwayorgsoIcansortoutwhethertomention-pforWindowsornot

YouLearnedThisYoursquoregettingintoprogrammerterritorywiththesecommandsbuttheyrsquoresohandyIhavetoteachthemtoyouThesecommandsletyoutemporarilygotoadifferentdirectoryandthencomebackeasilyswitchingbetweenthetwoThepushdcommandtakesyourcurrentdirectoryandldquopushesrdquoitintoalistforlaterthenitchangestoanotherdirectoryItrsquoslikesayingldquoSavewhereIamthengohererdquoThepopdcommandtakesthelastdirectoryyoupushedandldquopopsrdquoitofftakingyoubackthereFinallyonUnixpushdifyourunitbyitselfwithnoargumentsitwillswitchbetweenyourcurrentdirectoryandthelastoneyoupushedItrsquosaneasywaytoswitchbetweentwodirectoriesThisdoesnotworkinPowerShell

DoMorebullUsethesecommandstomovearounddirectoriesalloveryourcomputerbullRemovetheilikeicecreamdirectoriesandmakeyourownthenmovearoundinthem

bullExplaintoyourselftheoutputthatpushdandpopdwillprintoutforyouNoticehowitworkslikeastack

bullYoualreadyknowthisbutrememberthatmkdir-p(onLinuxmacOS)willmakeanentirepathevenifallthedirectoriesdonrsquotexistThatrsquoswhatIdidfirstforthisexercise

bullRememberthatWindowswillmakeafullpathanddoesnotneedthe-p

MakingEmptyFiles(touchNew-Item)Inthisexerciseyoulearnhowtomakeanemptyfileusingthetouch(New-ItemonWindows)command

DoThisLinuxmacOS

Exercise9Session

$cdtemp

$touchiamcooltxt

$ls

iamcooltxt

$

Windows

Clickheretoviewcodeimage

Exercise9WindowsSession

gtcdtemp

gtNew-Itemiamcooltxt-typefile

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12172011903AMiamcooltxt

gt

YouLearnedThisYoulearnedhowtomakeanemptyfileOnUnixtouchdoesthisanditalsochangesthetimesonthefileIrarelyuseitforanythingotherthanmakingemptyfilesOnWindowsyoudonrsquothavethiscommandsoyoulearnedhowtousetheNew-Itemcommandwhichdoesthesamethingbutcanalsomakenewdirectories

DoMorebullUnixMakeadirectorychangetoitandthenmakeafileinitThenchangeonelevelupandrunthermdircommandinthisdirectoryYoushouldgetanerrorTrytounderstandwhyyougotthiserror

bullWindowsDothesamethingbutyouwonrsquotgetanerrorYoursquollgetapromptaskingifyoureallywanttoremovethedirectory

CopyaFile(cp)Inthisexerciseyoulearnhowtocopyafilefromonelocationtoanotherwiththecpcommand

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise10Session

$cdtemp

$cpiamcooltxtneattxt

$ls

iamcooltxtneattxt

$cpneattxtawesometxt

$ls

awesometxtiamcooltxtneattxt

$cpawesometxtthefourthfiletxt

$ls

awesometxtiamcooltxtneattxtthefourthfiletxt

$mkdirsomething

$cpawesometxtsomething

$ls

awesometxtiamcooltxtneattxtsomethingthefourthfiletxt

$lssomething

awesometxt

$cp-rsomethingnewplace

$lsnewplace

awesometxt

$

Windows

Clickheretoviewcodeimage

Exercise10WindowsSession

gtcdtemp

gtcpiamcooltxtneattxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpneattxtawesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpawesometxtthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtmkdirsomething

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

gtcpawesometxtsomething

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtlssomething

DirectoryCUserszedtempsomething

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtcp-recursesomethingnewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gt

YouLearnedThisNowyoucancopyfilesItrsquossimpletojusttakeafileandcopyittoanewoneInthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectory

InthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectoryIrsquomgoingtotellyouasecretaboutprogrammersandsystemadministratorsnowTheyarelazyIrsquomlazyMyfriendsarelazyThatrsquoswhyweusecomputersWeliketomakecomputersdoboringthingsforusIntheexercisessofaryouhavebeentypingrepetitiveboringcommandssothatyoucanlearnthembutusuallyitrsquosnotlikethisUsuallyifyoufindyourselfdoingsomethingboringandrepetitivetherersquosprobablyaprogrammerwhohasfiguredouthowtomakeiteasierYoujustdonrsquotknowaboutityetTheotherthingaboutprogrammersistheyarenrsquotnearlyascleverasyouthinkIfyouoverthinkwhattotypethenyoursquollprobablygetitwrongInsteadtrytoimaginewhatthenameofacommandistoyouandtryitChancesarethatitrsquosanameorsomeabbreviationsimilartowhatyouthoughtitwasIfyoustillcanrsquotfigureitoutintuitivelythenaskaroundandsearchonlineHopefullyitrsquosnotsomethingreallystupidlikeROBOCOPY

DoMorebullUsethecp-rcommandtocopymoredirectorieswithfilesinthembullCopyafiletoyourhomedirectoryordesktopbullFindthesefilesinyourGUIandopentheminatexteditorbullNoticehowsometimesIputa(slash)attheendofadirectoryThatmakessurethefileisreallyadirectorysoifthedirectorydoesnrsquotexistIrsquollgetanerror

MovingaFile(mv)Inthisexerciseyoulearnhowtomoveafilefromonelocationtoanotherusingthemvcommand

DoThisLinuxmacOS

Exercise11Session

$cdtemp

$mvawesometxtuncooltxt

$ls

newplaceuncooltxt

$mvnewplaceoldplace

$ls

oldplaceuncooltxt

$mvoldplacenewplace

$ls

newplaceuncooltxt

$

Windows

Clickheretoviewcodeimage

Exercise11WindowsSession

gtcdtemp

gtmvawesometxtuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvnewplaceoldplace

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMoldplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvoldplacenewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gt

YouLearnedThisMovingfilesorratherrenamingthemItrsquoseasygivetheoldnameandthenewname

DoMoreMoveafileinthenewplacedirectorytoanotherdirectorythenmoveitback

ViewaFile(lessmore)TodothisexerciseyoursquoregoingtodosomeworkusingthecommandsyouknowsofarYoursquollalsoneedatexteditorthatcanmakeplaintext(txt)filesHerersquoswhatyoudo

bullOpenyourtexteditorandtypesomestuffintoanewfileOnmacOSthiscouldbeTextWranglerOnWindowsthismightbeNotepad++OnLinuxthiscouldbegeditAnyeditorwillwork

bullSavethatfiletoyourdesktopandnameittesttxtbullInyourshellusethecommandsyouknowtocopythisfiletoyourtempdirectorythatyoursquovebeenworkingwith

Onceyoursquovedonethatcompletethisexercise

Onceyoursquovedonethatcompletethisexercise

DoThisLinuxmacOS

Exercise12Session

$lesstesttxt

[displaysfilehere]

$

ThatrsquositTogetoutoflessjusttypeq(asinquit)Windows

Exercise12WindowsSession

gtmoretesttxt

[displaysfilehere]

gt

WarningIntheprecedingoutputIrsquomshowing[displaysfilehere]toldquoabbreviaterdquowhatthatprogramshowsIrsquolldothiswhenImeantosayldquoShowingyoutheoutputofthisprogramistoocomplexsojustinsertwhatyouseeonyourcomputerhereandpretendIdidshowittoyourdquoYourscreenwillnotactuallyshowthis

YouLearnedThisThisisonewaytolookatthecontentsofafileItrsquosusefulbecauseifthefilehasmanylinesitwillldquopagerdquosothatonlyonescreenfulatatimeisvisibleIntheDoMoresectionyoursquollplaywiththissomemore

DoMorebullOpenyourtextfileagainandrepeatedlycopy-pastethetextsothatitrsquosabout50ndash100lineslong

bullCopyittoyourtempdirectoryagainsoyoucanlookatitbullNowdotheexerciseagainbutthistimepagethroughitOnUnixyouuse

thespacebarandw(theletterw)togodownandupArrowkeysalsoworkOnWindowsjusthitthespacebartopagethrough

bullLookatsomeoftheemptyfilesyoucreatedtoobullThecpcommandwilloverwritefilesthatalreadyexistsobecarefulcopyingfilesaround

StreamaFile(cat)YoursquoregoingtodosomemoresetupforthisonesoyougetusedtomakingfilesinoneprogramandthenaccessingthemfromthecommandlineWiththesametexteditorfromthelastexercisecreateanotherfilenamedtest2txtbutthistimesaveitdirectlytoyourtempdirectory

DoThisLinuxmacOS

Exercise13Session

$lesstest2txt

[displaysfilehere]

$cattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

$cattesttxt

Hitherethisiscool

$

Windows

Exercise13WindowsSession

gtmoretest2txt

[displaysfilehere]

gtcattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

gtcattesttxt

Hitherethisiscool

gt

RememberthatwhenIsay[displaysfilehere]IrsquomabbreviatingtheoutputofthatcommandsoIdonrsquothavetoshowyouexactlyeverything

YouLearnedThisDoyoulikemypoemTotallygoingtowinaNobelAnywayyoualreadyknowthefirstcommandandIrsquomjusthavingyoucheckthatyourfileisthereThenyoucatthefiletothescreenThiscommandjustspewsthewholefiletothescreenwithnopagingorstoppingTodemonstratethatIhaveyoudothistotesttxtwhichshouldjustspewabunchoflinesfromthatexercise

DoMorebullMakeafewmoretextfilesandworkwithcatbullUnixTrycattesttxttest2txtandseewhatitdoesbullWindowsTrycattesttxttest2txtandseewhatitdoes

RemovingaFile(rm)Inthisexerciseyoulearnhowtoremove(delete)afileusingthermcommand

DoThisLinux

Clickheretoviewcodeimage

Exercise14Session

$cdtemp

$ls

uncooltxtiamcooltxtneattxtsomethingthefourthfiletxt

$rmuncooltxt

$ls

iamcooltxtneattxtsomethingthefourthfiletxt

$rmiamcooltxtneattxtthefourthfiletxt

$ls

something

$cp-rsomethingnewplace

$

$rmsomethingawesometxt

$rmdirsomething

$rm-rfnewplace

$ls

$

Windows

Clickheretoviewcodeimage

Exercise14WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtrmuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtrmiamcooltxt

gtrmneattxt

gtrmthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

gtcp-rsomethingnewplace

gtrmsomethingawesometxt

gtrmdirsomething

gtrm-rnewplace

gtls

gt

YouLearnedThisHerewecleanupthefilesfromthelastexerciseRememberwhenIhadyoutrytormdironadirectorywithsomethinginitWellthatfailedbecauseyoucanrsquotremoveadirectorywithfilesinitTodothatyouhavetoremovethefileorrecursivelydeleteallofitscontentsThatrsquoswhatyoudidattheendofthis

DoMorebullCleanupeverythingintempfromalltheexercisessofarbullWriteinyournotebooktobecarefulwhenrunningrecursiveremoveonfiles

ExitingYourTerminal(exit)DoThisLinuxmacOS

Exercise23Session

$exit

Windows

Exercise23WindowsSession

gtexit

YouLearnedThisYourfinalexerciseishowtoexitaTerminalAgainthisisveryeasybutIrsquomgoingtohaveyoudomore

DoMore

ForyourlastsetofexercisesIrsquomgoingtohaveyouusethehelpsystemtolookupasetofcommandsyoushouldresearchandlearnhowtouseonyourownHerersquosthelistforUnix

bullxargsbullsudobullchmodbullchown

ForWindowslookupthesethingsbullforfilesbullrunasbullattribbullicacls

Findoutwhattheseareplaywiththemandthenaddthemtoyourindexcards

CommandLineNextStepsYouhavecompletedthecrashcourseAtthispointyoushouldbeabarelycapableshelluserTherersquosawholehugelistoftricksandkeysequencesyoudonrsquotknowyetandIrsquomgoingtogiveyouafewfinalplacestogoresearchmore

UnixBashReferencesTheshellyoursquovebeenusingiscalledBashItrsquosnotthegreatestshellbutitrsquoseverywhereandhasalotoffeaturessoitrsquosagoodstartHerersquosashortlistoflinksaboutBashyoushouldgoread

BashCheatSheethttpslearncodethehardwayorgunixbash_cheat_sheetpdf(createdbyRaphaelandCClicensed)

ReferenceManualhttpwwwgnuorgsoftwarebashmanualbashrefhtml

PowerShellReferencesOnWindowstherersquosreallyonlyPowerShellHerersquosalistofusefullinksforyourelatedtoPowerShell

OwnerrsquosManualhttptechnetmicrosoftcomen-uslibraryee221100aspx

CheatSheethttpsdownloadmicrosoftcomdownload2122122F0B9-0EE6-4E6D-BFD6-F9DCD27C07F9WS12_QuickRef_Download_FilesPowerShell_LangRef_v3pdf

MasterPowerShellhttppowershellcomcsblogsebookdefaultaspx

Index

Symbols(colon)creatingfunctions61ndash62(dot)operator146ndash148193(double-quotes)avoidusingwithTrueFalse31createstrings26ndash27createstringswithsingle-quotesvs29escapinginsidestrings34ndash36promptandpass47

gt=(greater-than-equal)operator16ndash1797+=(incrementby)operator69ndash70105lt=(less-than-equal)operator16ndash1797-(minus)operator16ndash17=(notequal)operator97ndash98100ndash102(single-quotes)createstrings26ndash27createstringswithdouble-quotesvs29escapinginsidestrings34ndash36indicatingstrings57

(triple-single-quotes)36(triple-quotes)dedentfunction170ndash175errorswhenputtingspacesbetween33escapinginsidestrings3436

(slash)character16ndash17257(backslash)character33ndash34257(doublebacklash)character36_(underscore)character20ndash2162189+(plus)operator16ndash1754==(equal)operatorfunctionof21

practicingBooleanlogic100ndash102intruthtables98astruthterm97

=(single-equal)operator21(poundoroctothorpe)character1214ndash1517(percent)operator1617ndash18(asterisk)operator16ndash17[]leftandrightbracketslists112ndash114^(caret)characterviewoutput11charactersembeddedvariablesinstrings24ndash25lt(lessthan)operator16ndash17ltgt=(notequal)vs102gt(greaterthan)operator16ndash1791

AactivatescriptPowershell195Addressesweb225altered()functioninheritance180ndash183Alternativetexteditors6ndash7and

inBooleanlogic100ndash102astruthterm96ndash98

apppy

buildfirstwebsite217ndash221creategameengine239ndash241createHTMLforms228ndash229howformswork226ndash227writeautomatedtestsforforms231ndash232

app_testspyfile231241aproposcommand252args60ndash62Argumentscreatingfunctions6266argv

asargumentvariable42

promptingandpassingusing46ndash47readingandwritingfiles54readingfiles48ndash50unpacking42ndash44usinginput()vs44

Arrayslistsvs114ASCII(AmericanStandardCodeforInformationInterchange)80ndash81assert_equal()functionautomatedtesting201ndash203assert_raises()functionwritingtestexpectedtofail215asterisk()operator16ndash17Atomtexteditoralternativesto6ndash7Linuxsetup4ndash5macOSsetup2Windowssetup3ndash4workingwithfirstprogram9

Automatedtestsforforms232improving242overviewof200ndash203refactoringgothonwebgameusing238ndash239testfirstwith206ndash207

BBackslash()character33ndash34257Bashreferences283Big5encoding85bindirectoryskeletonprojectdirectory198Bits8182Blocksofcode106ndash110Booleanlogicmemorizingvslearning98practicing100ndash102rulesforif-statements126

Bottomupprocessesvstopdown169Brackets([])lists112ndash114Branchesandfunctions122ndash124Breakingfiles8592232Browsercreateenginetorungamein234ndash241gettinginputfromSeeInputgettingfrombrowserhowitaccessesinformation225ndash226

Bytesbreakingfiles85conventionsforencoding80ndash81defined78dissectingcode82ndash84dissectingoutput82

CC3algorithmsuper()function183Cardinalnumberslists120ndash121137caret(^)characterviewoutput11catcommandprintwholefile57252278ndash279cdcommandchangedirectorymacOSLinux251overviewof258ndash260Windows252

cd~command255CharactersencodingSeeStringsbytesandcharacterencodingsimportanceoflearningnamesof76fortruthterms96ndash97

Checklistcreatingfunction62ChildclassesSeeInheritancevscompositionClassesaddsconsistencytoprogram146asblueprintsfornewmini-modules149codeandtestinOOP167ndash169

designhierarchyinOOP166ndash167inheritancevscompositionSeeInheritancevscompositionobject-orientedphrasedrill152ndash153object-orientedreadingtest154ndash155object-orientedworddrill152researchingPython137similaritytomodules147ndash148styling189astemplatesmintingnewobjects186

CLI(commandlineinterface)usingonGUI261closecommandclosefile52ndash53Codeavoidhardcodingfilenames48blocksof106ndash107classestesting167ndash169createonelineof57findingerrorsin132inheritancevscompositionforreusable185OOPanalysisanddesign170ndash176parser211ndash214practicingEnglishto155reading132readingbackwardSeeReadingcodebackwardreadingphrases156refactoringforgothonwebgame234ndash239researchingpieceof78styling190testingotherprogrammerrsquos94typingintoTerminalPowerShell50

Colon()creatingfunctions61ndash62Colorsintexteditors12Command-linecrashcoursechangedirectory(cd)258ndash261copyfile(cp)272ndash275

exityourterminal(exit)282howtouseappendix248ndash249introduction248listdirectory(ls)261ndash265makedirectory(mkdir)255ndash257makeemptyfiles(touchNew-Item)271ndash272memorizingthings249movearound(pushdpopd)268ndash271movefile(mv)275ndash276pathsfoldersdirectories(pwd)253ndash255PowerShellreferences283removedirectory(rmdir)265ndash268removefile(rm)280ndash281setup249ndash253streamfile(cat)278ndash279UnixBashreferences283viewfile(lessmore)277ndash278

Commandlineinterface(CLI)usingonGUI261Commandsconvertingargumentstostrings44asfunctionsandmethods50learning44

Commentsaddingwhenreadingcode132creatingfunctionswith65ndash66designingdebuggingwith127functionsfileswith69gettinghelpwithdocumentation92is-ahas-arelationshipsusing159ndash160readingwritingfilesusing53usinginPython14ndash15variablenames21writinggood190writingwhenyoudonotunderstandcode29124

Composition

Compositiondefined152overviewof184ndash185whentouseinheritanceor185

Connectionsweb225ndash226Conventionsforencodingtext80ndash81Copyingfileswritingscriptfor56ndash58cpcopyfileordirectorymacOSLinux251overviewof272ndash275Windows252

curlcommandgeneraterequesttypes232

DDatastructuresdictionariesas140ndash144listsascommon136ndash137

Datatypeslistof129DBES(DecodeBytesEncodeStrings)dissectingcode83ndash84Debuggingdesigningand126ndash127fixingerrorsinfirstwebsite219refactoredcode241

Decisionsmaking108ndash110dedent()function-stylestrings170ndash175def(createfunction)branchesandfunctions122ndash124creategameengine239ndash241defined152filesworkingwithfunctions68ndash70functionscanreturnsomething72ndash74functionsworkingwithvariables90ndash93is-ahas-arelationships159ndash160overviewof60ndash62inreadingtest154ndash155

delkeyworddeletefromdictionary141Designinganddebugging126ndash127dict

howformswork227understandingdictionaries140ndash144

Dictionariesexampleof141ndash143functionsof143ndash144listsvs140ndash141modulessimilarto146ndash147storescenesbynamein175

diefunctionif-statementrules126dir-rfindfilesinWindows253DirectoriescausesofImportErrors209ldquoHelloWorldrdquowebapplication217LinuxmacOScommand-linefor251skeletonprojectSeeSkeletonprojectdirectoryWindowscommand-linefor252

DjangoTutorial244Documentationcheckoutprojectsbuildsomethingusing244gettinghelpwithcomments92writinggoodcomments190

Dot()operator146ndash148193Doublebacklash()36Double-quotesSee(double-quotes)

Eechoprintsomearguments252253Elementsaccessinglist120ndash121elif

branchesandfunctions122ndash124andelse107makingdecisions108ndash110

else

branchesandfunctions122ndash124andif-statement106ndash107makingdecisions108ndash110rulesforif-statements126

Encodingsbytescharacter80ndash85envcommandlookatyourenvironment252EqualoperatorSee==(equal)operatorErrormessagesbuildingfirstwebsite218ndash219EOFError155ImportErrorSeeImportErrorsNameError47ParserError211ndash214printing29forspacesbetweentriple-quotes33forspellingmistakes33ValueErrorSeeValueErrorsvariablenames21viewingoutputinfirstprogram11whenmakingscriptshorter58

Escapesequencesfordifferentcharactersinstrings34ndash35practicing87readingandwritingfiles54reviewing130supportedbyPython35

exceptkeywordexceptions206Exceptionshowtoraise211ndash214andnumbers206

existscommandcopyingfiles56ndash58exitcommandexitshell124252282exportcommandexportnewenvironmentvariable252

F

Ffcharacterembeddingvariablesinsidestrings24ndash25promptingandpassing46ndash47inreadline()70usingwithfunctions69

Falsekeywordavoidquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98

Featuresaddingtoscript42alsocalledmodules42ndash43

FileTransferProtocol(FTP)andURLs225Filenames48ndash50Filescopying56ndash58creating50andfunctions68ndash70LinuxmacOScommand-linefor251ndash252reading48ndash50readingandwriting52ndash54Windowscommand-linefor252ndash253

findcommandfiles252Firstprogramcreate8ndash12flaskframeworkcreatebasictemplatesforwebsite219ndash221creategameengine239ndash241fixerrors218ndash219ImportErrorafterinstalling222installingforfirstwebsite216makeldquoHelloWorldrdquowebapplication216ndash217testingtricksforcreatingfakesessions242webpyvs221

whatisgoingon218FLASK_DEBUGnotsafetoactivateonInternet219Flowcharts132FoldersSeeDirectoriesfooOOP152for-loops

buildinglistswith112ndash114rulesfor126whentouselists137while-loopsvs118

forOOP154ndash155forfiles253formatfunction30ndash31Formatstringsformatterformat()30oldstyle130ndash131overviewof24ndash25readingandwritingfiles54

format()syntaxformattingstrings26ndash2730Formsautomatedtestsfor232creatingHTML227ndash229howtheywork226ndash227

FTP(FileTransferProtocol)andURLs225Functionsaccessinginmodulewith(dot)operator146ndash147alsocalledmethodscommands50branchesand122ndash124canreturnsomething72ndash74createchecklistfor62andfiles68ndash70overviewof60ndash62practicing87ndash8890ndash93readingcode132

replicatingimplicitinheritance184ndash185styling189usingprintvsreturnin93andvariables64ndash6687ndash88viewingcalls137

GGamestartofyourwebcreatingengine239ndash241overviewof234refactoring234ndash239yourfinalexam241ndash242

GamesanalysisanddesignSeeObject-orientedanalysisanddesignmakingyour188ndash191

gothonwebprojectanalysisofsimplegameengine165ndash169codefor170ndash176creatinglayouttemplate234ndash239makingintofirstwebapplication217ndash221refactoringcodecreatingwebenginetorun234ndash241

Grammarmakingsentences211215Greater-than-equal(gt=)operator16ndash1797Greaterthan(gt)operator16ndash1791grepcommandfindthingsinsidefiles252GUI(graphicaluserinterface)usingCLIon261

HHardcodedfilenamesavoid48has-arelationships152158ndash162ldquoHelloWorldrdquowebapplicationcreatebasictemplates219ndash221fixingerrors218ndash219

Helpcreatesystemfor242

gettingmodule92helpcommandWindows253helpctrcommandWindows253Hierarchyclass166ndash169hostname

mycomputerrsquosnetworkname251252understandURLs225

HTMLcreatebasictemplatesforwebsite219ndash221createforms227ndash229creategameengine239ndash241improveappearanceof242research232understandresponse226

HTTPrequests218244researchHTTPREC232understandURLs225

IIDLEavoidusing1231if-elsetry-exceptvs209if-statements

branchesandfunctions122ndash124elseand106ndash107loopsandlists112ndash114makedecisions83ndash84108ndash110overviewof104ndash105readcode132rulesfor126

Implicitinheritancecombinewithothertypesofinheritance182compositionvs184ndash185overviewof178ndash179

import

addfeaturestoscript42copyfiles56ndash58filewithmodules146makeagameyourself188objectsassimilarto148ndash149

ImportErrorsafterinstallingflask222causesof209242createskeletonprojectdirectory199

Incrementby(+=)operator69ndash70105Indentation61ndash62106index()

creategameengine239ndash241createHTMLforms229howformswork227

indexGEThandler224Inheritanceavoidmultiple178183185object-orientedphrasedrill152object-orientedreadingtest154ndash155object-orientedworddrill152

Inheritancevscompositionalterbehaviorbeforeorafter180ndash181implicitinheritance179overrideexplicitly180overviewof178reasonforsuper()183threekindsofinheritancecombined182ndash183understandcomposition184ndash185understandinheritance178ndash179usinginheritancevscomposition185usingsuper()with__init__()183

__init__functioninitializingnewlycreatedemptyobject149

inis-ahas-arelationships159ndash162runningreliablyforparentclass162tryingnottodotoomuchin189usingselfwhenmakingfunctionsforclasses151usingsuper()in183

input()

askingquestions38ndash39enteringownvalues74parameterto(gt)124parametersunpackingvariables42ndash44promptingandpassing46ndash47promptingpeople40ndash41readingfiles48ndash50

Inputadvanceduserourgamelexicon204ndash206overviewof204testfirstchallenge206ndash207whatyoushouldtest207ndash209

Inputgettingfrombrowserbreakingit232creatingHTMLforms227ndash229creatinglayouttemplate229ndash230howformswork226ndash227howwebworks224ndash226writingautomatedtestsforforms232

ltinputgttags229ndash230Instance152ndash153Instantiation148ndash149Internetflaskdebuggermodenotsafeon219Internetresearchcheckoutprojectstrytobuildsomething244findthings5ndash6functionsandfiles69importstatement57

object-orientedprogramming137151pydoc40ndash41readingfiles49

int()functionconvertingcommandlineargumentstrings44IPaddressesandURLs225is-arelationships152158ndash162

JJinja2Documentationtemplatelanguage221

KKeywordslistof128ndash129Kivy244

LLayouttemplatecreate232LearnCTheHardWay244LearnRubyTheHardWay244len()function5658lesscommandviewfileinmacOSLinux252277ndash278Less-than-equal(lt=)operator16ndash1797Lessthan(lt)operator16ndash17LexiconcreatinggamemakesentencesSeeSentencesmakingoverviewof204ndash206testfirstchallenge206ndash207whatyoushouldtest207ndash209

Librariesdefined43LinuxmacOSalternativetexteditorsfor7getterminalopenandworking250ndash251projectskeletonsetup192ndash194setupexercise4ndash5

LinuxmacOScommand-linecatstreamfile278ndash279

cdchangedirectory258ndash259261cpcopyfileordirectory272274ndash275exitexitshell282lessviewfile277ndash278listofcommands251ndash252lslistdirectory262265mkdirmakedirectory256ndash257mvmovefileordirectory275277pushdpopd(movedirectory)268ndash271pwdprintworkingdirectory253ndash255rmstreamfile278ndash279rmdirremovedirectory266268

Listsaccesselementsof120ndash121buildusingfor-loops112ndash114doingthingsto134ndash138making2-D114processinglistsofthings78whentouse137

localhost

buildfirstwebsite218221webconnection225

Logicmemorizing96ndash98practicingBoolean100ndash102

Loginresearchingwebapplication242Lookuptablesdictionariesas144Loopsandlists112ndash114for-loopsSeefor-loopsmakinginfinite124rulesfor126ndash127while-loopsSeewhile-loops

lpthwvirtualenvironmentskeletonproject193195

lslistdirectorymacOSLinux251overviewof261ndash265Windows252

MmacOSSeeLinuxmacOSmainfunctiondissectingcode83manreadmanualpageinmacOSLinux252Mapclassgothonwebprojectcode171storingscenesbynameindictionary175

Mapsanalysisofsimplegameengine165completinggame242withdictionaries143ndash144

matchfunctionparsercode212Math16ndash1839Memorizationofcommandsusingindexcards251ndash253learningcommandline249oflogic96ndash98tipsfor96

Methodresolutionorder(MRO)super()183Methodsalsocalledfunctionsandcommands50functionsvs189

Minus(--)operator16ndash17mkdirmakedirectorymacOSLinux251overviewof255ndash257Windows252

Modifiersreadingandwritingfiles54ModulescausesofImportErrors209

gettinghelpfor92overviewof146ndash147replicatingimplicitinheritancein184ndash185usingclassesvs147ndash148

morecommandviewfileinWindows252278MRO(methodresolutionorder)super()183Multipleinheritanceavoid178183185mvcommandmovefileordirectorymacOSLinux251overviewof275ndash277Windows252

NNameErrormessage47Namescreatingfunction62189definemodules42ndash43filenames48ndash50importanceoflearningsymbol76variable20ndash2260ndash62

NaturalLanguageToolKit244Nestedstructureslistsas112rulesforif-statements126

new-itemcommandcreateemptyfilesinWindows271ndash272Noneforsomefunctions93nosetestscommandautomatedtests201ndash203automatedtestsforforms231createskeletonprojectdirectory197ndash199syntaxerror203

not

inBooleanlogic100ndash102intruthtables97ndash98

astruthterm97Notequal(=)operator97ndash98100ndash102Nounsobject-orientedprogramming164ndash167Numbersaccesselementsoflists120ndash121exceptionsand206indexlistsinto140ndash141inputtodomath39andmath16ndash18betweenrangeofnumbers110roundingfloatingpoint25

OObject-orientedanalysisanddesignSeealsoGamestartofyourwebanalysisofsimplegameengine165codeclassesandtesttorunthem167ndash169codeforldquoGothonsfromPlanetPercal25rdquo170ndash176createclasshierarchyobjectmapforconcepts166ndash167extractresearchkeyconcepts166overviewof164ndash165repeatandrefine169topdownvsbottomup169whatyoushouldsee176writeordrawaboutproblem165

Object-orientedprogramming(OOP)inheritancevscompositionSeeInheritancevscompositionPythonas146research137151speak152ndash156

Objectsclassesastemplatesthatmintnew186makesentenceswith210ndash211object-orientedphrasedrill152ndash153object-orientedworddrill152parsercode212ndash215

similartoimport148ndash149Octothorpe()character1214ndash1517opencommandreadingandwritingfiles52ndash54OperatorsfindingmorePythonequality102listof131ndash132math16ndash17variablename20ndash22

or

inBooleanlogic100ndash102intruthtables97ndash98astruthterm96

Ordermaintainwithlists137Ordinalnumberslists120ndash121Outputoffirstprogram10ndash11ldquoHelloWorldrdquowebapplication217

override()functioninheritance189

PPandas244Paragraphsif-statementrules126Parametersreadingandwritingfiles54ParentclassesSeeInheritancevscompositionParsercode211ndash214playingwith214ndash215

ParserErrorexception211ndash214Passingpromptingand46ndash47PEMDASacronymorderofmathoperations18Percent()operator1617ndash18Phrasedrillsobject-oriented152ndash156pip36(orjustpip)createskeletonprojectdirectory192ndash195198ndash199installflasktobuildfirstwebsite216

planispherepyfile234ndash238

planisphere_testspyfile238ndash239Plus(+)operator16ndash1754popdcommandpopdirectorymacOSLinux251overviewof268ndash271Windows252

Portswebconnections225POSTautomatedtestsforforms231creatingHTMLforms227ndash229

Pound()character1214ndash1517PowerShellcreategameengine240infirstprogram11ndash12references283typingcodeinto50Windows10setupfor3ndash4195250ndash251

print

debugwith127readcodeusing132whenfunctionsusereturnvs93

Printstringswithmorecomplicatedformatting30ndash31moreexercisesin28ndash2932ndash33usingescapesequences34ndash36variables24ndash25

print_a_linepassincurrentlinenumber68ndash69print_linefunctiondissectingcode83ndash84print_twofunctioncreatefunctions60ndash61Programminglanguagesadvicefromoldprogrammer246ndash247checkoutprojectstrytobuildsomething244howtolearnnew245learningcommandlineSeeCommand-linecrashcourse

Projectskeleton192ndash194Promptsidentifyinappendixexercises254andpassing46ndash47people40ndash41

Prototypelanguages186Pseudocodetestfirstusing207pushdcommandpushdirectorymacOSLinux251overviewof268ndash271Windows252

pwdcommandprintworkingdirectorymacOSLinux251overviewof253ndash255Windows252

pyfilespassingvariablestoscript42ndash44pydoccommandpromptpeople40ndash41PyGame244PYTHONPATHenvironmentvariable240

Qquit()functionreloadPythonafter92

Rraisekeywordexceptions211213ndash214range()functionloops114Rawbytes7982ndash84readcommandreadcontentsoffile52ndash54Readingcode132codeoutloud190files48ndash50andwritingfiles52ndash54

Readingcodebackwardcommentsandpoundcharacters14

defined88printing29reasonsfor15understandinghowto22

readline()function52ndash53687083Refactoringcode234ndash239render_template()function220ndash221requestargsforms227Requestswebgeneratingtypesofwithcurl232learnclientsideofHTTP244process224ndash225understand225

Responsesweb226return

functions72ndash74object-orientedreadingtest155whenfunctionsuseprintvs93

rmstreamfile280ndash281rmdircommandremovedirectorymacOSLinux251overviewof265ndash268Windows252

Roomclassautomatedtests201ndash203creategameengine239ndash241refactorcodeforgothonwebgame234ndash239

round()functionfloatingpointnumbers25Rulesforif-statements126forloops126ndash127whentouseinheritanceorcomposition185

runascommanddangerinwindows252

S

Scanninginputlexicontuples205209Scenes(rooms)analysisofsimplegameengine165ndash167codeclassesforsimplegame167ndash169gothonwebprojectcode170ndash176makinggameyourself188ndash191whatyoushouldsee176

SciPy244ScraPy244Scriptslinkingfunctionsto61makingdecisions107passingvariablesto42ndash44

SearchenginesfindingthingsonInternet5ndash6howtotype(octothorp)character15

seek()functiondefined52ndash53doesnotsetcurrentlineto070researchforfile69

select-stringcommandfindthingsinsideWindowsfiles253self

__init__function148151is-ahas-arelationshipsand159ndash160object-orientedlanguage152ndash155

Sentencesmakingbreakingup205exceptions211grammar211matchandpeek210ndash211overviewof210parsercode211ndash215whatyoushouldtest215

Servershowbrowsersaccessinformationon226

setcommandexportsetnewenvironmentvariableinWindows253Setupexercisealternativetexteditors6ndash7findingthingsonInternet5ndash6Linux4ndash5macOS2ndash3overviewof2warningsforbeginners6Windows3ndash4

setuppyfileskeletonprojectdirectory196198ndash199Single-equal(=)operator21Single-quotesSee(single-quotes)Skeletonprojectdirectoryautomatedtesting200ndash203creatingdirectorystructure195ndash197macOSLinuxsetup192ndash194overviewof192requiredquiz198testingsetup197ndash198using198Windows10setup194ndash195

skipkeywordparsercode213Slash()character16ndash17257Spaceaddingaroundoperatorsforeasierreading22makecodereadablewithvertical190

Spellingmistakeserrormessagesfor33Stopwordsparsercode213Stringsacrossmultiplelines34ndash36complicatedformattingof30ndash31convertcommandlineargumentsto44decodebytesandencode83ndash84embedvariablesinside24ndash25

exerciseinprinting28ndash29listofescapesequencesfor130listofoldstyleformatsfor130ndash131listsmixedwith135ndash136poundcharactersin15readwritefilesin54startnewlinein33andtext26ndash27understanding26asUTF-8encodedsequenceofcharacters82

Stringsbytesandcharacterencodingsbreakingit85dissectcode82ndash84dissectoutput82encodingsdeepdive84ndash85initialresearch78ndash80overviewof78switchesandconventions80ndash81

Stylingcode190functionsandclasses189

Subjectparsercode212ndash215ofsentences210ndash211

sudocommand252super()functioninheritance180ndash183Switches80ndash81Symbolsdatatypes129escapesequencesforstrings130keywords128ndash129learningnamesof76oldstylestringformats130ndash131operators131ndash132readingcode132

SyntaxErrormessageEOL58invalidsyntax1293promptingandpassing47pydoc41viewingoutputinfirstprogram11

Systemsitepackagessetupforskeletonproject193

TTablesdictionariesaslookup144truth97ndash98

Templatescreatebasic219ndash221creategameengine239ndash241createHTMLforms229createlayout229ndash230

templatesindexhtmlfile219ndash221229ndash230templateslayouthtmlfile230TensorFlow244Terminalgettingopenandworking250ndash251Linuxsetup5macOSsetup2ndash3typingcodeinto50whatyoushouldseeinfirstprogram9ndash11Windowssetup3ndash4

Terminologytruth96ndash97webapplication225ndash226

Testcasewriting200ndash201Testfirstprogrammingtactic206ndash207Test_directionstestcase207ndash209TestsSeealsoAutomatedtestsBooleanlogic100ndash102

codeforclassesinOOP168ndash169object-orientedreading153ndash155otherprogrammerrsquoscode94session-basedgameengine241skeletonprojectdirectorysetup197ndash198tricksforcreatingfakesessionsinside242

testsapp_testspy231Testtxtfilecopyingfiles56ndash58Textreadingfiles48ndash50andstrings26ndash27

Texteditorsalternative6ndash7gettingcolorsin12Linuxsetup4ndash5macOSsetup2

Thingsgettingthingsfrom149ndash150TopdownprocessOOPdesign164vsbottomup169

touchcommandmakeemptyfilesinmacOSLinux271ndash272Tracingvariablesreadingcode132Triple-quotes()See(triple-quotes)Triple-single-quotes()36Truekeywordavoidputtingquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98astruthterm97

truncatecommand52ndash54Truthtables97ndash98terms96ndash97

try-exceptif-elsevs209

trykeywordexceptions206Tupleslexicon205typecommandprintwholefileinWindows252

UUnderscore(_)character20ndash2162189Unicode81URLs(UniformResourceLocators)buildfirstwebsite218createHTMLforms228howformswork227overviewof225

UserinputSeeInputadvanceduserUserWarningwhenrunningnosetests203UTF-16standard84ndash85UTF-8standardcomparingUTF-16UTF-32to84ndash85dissectingoutput82encodingtextinPython81fixingterminalunabletodisplay79stringsinPython82ndash84

VValueErrorsandnumbers206parametersunpackingvariables44promptingpassing47

Variablesaccessinmodule146ndash147avoidmoduleorglobal189andfunctions64ndash66for-loopusingundefined114andnames20ndash22andnamescodefunctions60ndash62passingtoscript42ndash44

practicing90ndash93printing24ndash25promptingandpassing46ndash47readingcode132temporarilyinsidefunctions87ndash88writingstringswithtext26ndash27

venvsdirectoryskeletonprojectsetup193ndash195VerbsanalyzeclasshierarchyinOOP165extractkeyconceptsinOOP164makesentenceswith210ndash211parsercode212ndash215

virtualenv192ndash193194

WWarningsforbeginners5ndash6setup2

Webbreakingapplications232howitworks224ndash226learnclientsideof244startofyourgameSeeGamestartofyourweb

Websiteyourfirstcreatebasictemplates219ndash221fixingerrors218ndash219installflaskframework216makeldquoHelloWorldrdquowebapplication216ndash217whatisgoingon218

while-loops

overviewof116ndash118readingcode132rules126whentobreakruleaboutnotusing138

whileTruemakeinfiniteloop124Windows

Windowsalternativetexteditorsfor7setupexercise3ndash4skeletonprojectdirectorysetup194ndash195

Windowscommand-linecatstreamfile259ndash261278ndash279cpcopyfileordirectory272ndash275exitexitshell282gettingPowerShellopenandworkingfor250ndash251listofcommands252ndash253lslistdirectory262ndash265macOSsetup2moreviewfile278mvmovefileordirectory275ndash277pushdpopd(movedirectory)269ndash271pwdprintworkingdirectory254ndash255rmstreamfile278ndash279rmdirremovedirectory266ndash268

Worddrillsobject-oriented152ndash155wordspopfunction93Writeformulasusingfunctions74andreadfiles52ndash54

Xxargscommandexecutearguments252

CodeSnippets

ManytitlesincludeprogrammingcodeorconfigurationexamplesTooptimizethepresentationoftheseelementsviewtheeBookinsingle-columnlandscapemodeandadjustthefontsizetothesmallestsettingInadditiontopresentingcodeandconfigurationsinthereflowabletextformatwehaveincludedimagesofthecodethatmimicthepresentationfoundintheprintbookthereforewherethereflowableformatmaycompromisethepresentationofthecodelistingyouwillseealdquoClickheretoviewcodeimagerdquolinkClickthelinktoviewtheprint-fidelitycodeimageToreturntothepreviouspageviewedclicktheBackbuttononyourdeviceorapp

  • About This eBook
  • Title Page
  • Copyright Page
  • Contents
  • Preface
    • Improvements in the Python 3 Edition
    • The Hard Way Is Easier
      • Reading and Writing
      • Attention to Detail
      • Spotting Differences
      • Ask Donrsquot Stare
      • Do Not Copy-Paste
      • Using the Included Videos
      • A Note on Practice and Persistence
        • Acknowledgments
          • Exercise 0 The Setup
            • macOS
              • macOS What You Should See
                • Windows
                  • Windows What You Should See
                    • Linux
                      • Linux What You Should See
                        • Finding Things on the Internet
                        • Warnings for Beginners
                        • Alternative Text Editors
                          • Exercise 1 A Good First Program
                            • What You Should See
                            • Study Drills
                            • Common Student Questions
                              • Exercise 2 Comments and Pound Characters
                                • What You Should See
                                • Study Drills
                                • Common Student Questions
                                  • Exercise 3 Numbers and Math
                                    • What You Should See
                                    • Study Drills
                                    • Common Student Questions
                                      • Exercise 4 Variables and Names
                                        • What You Should See
                                        • Study Drills
                                        • Common Student Questions
                                          • Exercise 5 More Variables and Printing
                                            • What You Should See
                                            • Study Drills
                                            • Common Student Questions
                                              • Exercise 6 Strings and Text
                                                • What You Should See
                                                • Study Drills
                                                • Break It
                                                • Common Student Questions
                                                  • Exercise 7 More Printing
                                                    • What You Should See
                                                    • Study Drills
                                                    • Break It
                                                    • Common Student Questions
                                                      • Exercise 8 Printing Printing
                                                        • What You Should See
                                                        • Study Drills
                                                        • Common Student Questions
                                                          • Exercise 9 Printing Printing Printing
                                                            • What You Should See
                                                            • Study Drills
                                                            • Common Student Questions
                                                              • Exercise 10 What Was That
                                                                • What You Should See
                                                                • Escape Sequences
                                                                • Study Drills
                                                                • Common Student Questions
                                                                  • Exercise 11 Asking Questions
                                                                    • What You Should See
                                                                    • Study Drills
                                                                    • Common Student Questions
                                                                      • Exercise 12 Prompting People
                                                                        • What You Should See
                                                                        • Study Drills
                                                                        • Common Student Questions
                                                                          • Exercise 13 Parameters Unpacking Variables
                                                                            • Hold Up Features Have Another Name
                                                                            • What You Should See
                                                                            • Study Drills
                                                                            • Common Student Questions
                                                                              • Exercise 14 Prompting and Passing
                                                                                • What You Should See
                                                                                • Study Drills
                                                                                • Common Student Questions
                                                                                  • Exercise 15 Reading Files
                                                                                    • What You Should See
                                                                                    • Study Drills
                                                                                    • Common Student Questions
                                                                                      • Exercise 16 Reading and Writing Files
                                                                                        • What You Should See
                                                                                        • Study Drills
                                                                                        • Common Student Questions
                                                                                          • Exercise 17 More Files
                                                                                            • What You Should See
                                                                                            • Study Drills
                                                                                            • Common Student Questions
                                                                                              • Exercise 18 Names Variables Code Functions
                                                                                                • What You Should See
                                                                                                • Study Drills
                                                                                                • Common Student Questions
                                                                                                  • Exercise 19 Functions and Variables
                                                                                                    • What You Should See
                                                                                                    • Study Drills
                                                                                                    • Common Student Questions
                                                                                                      • Exercise 20 Functions and Files
                                                                                                        • What You Should See
                                                                                                        • Study Drills
                                                                                                        • Common Student Questions
                                                                                                          • Exercise 21 Functions Can Return Something
                                                                                                            • What You Should See
                                                                                                            • Study Drills
                                                                                                            • Common Student Questions
                                                                                                              • Exercise 22 What Do You Know So Far
                                                                                                                • What You Are Learning
                                                                                                                  • Exercise 23 Strings Bytes and Character Encodings
                                                                                                                    • Initial Research
                                                                                                                    • Switches Conventions and Encodings
                                                                                                                    • Disecting the Output
                                                                                                                    • Disecting the Code
                                                                                                                    • Encodings Deep Dive
                                                                                                                    • Breaking It
                                                                                                                      • Exercise 24 More Practice
                                                                                                                        • What You Should See
                                                                                                                        • Study Drills
                                                                                                                        • Common Student Questions
                                                                                                                          • Exercise 25 Even More Practice
                                                                                                                            • What You Should See
                                                                                                                            • Study Drills
                                                                                                                            • Common Student Questions
                                                                                                                              • Exercise 26 Congratulations Take a Test
                                                                                                                                • Common Student Questions
                                                                                                                                  • Exercise 27 Memorizing Logic
                                                                                                                                    • The Truth Terms
                                                                                                                                    • The Truth Tables
                                                                                                                                    • Common Student Questions
                                                                                                                                      • Exercise 28 Boolean Practice
                                                                                                                                        • What You Should See
                                                                                                                                        • Study Drills
                                                                                                                                        • Common Student Questions
                                                                                                                                          • Exercise 29 What If
                                                                                                                                            • What You Should See
                                                                                                                                            • Study Drills
                                                                                                                                            • Common Student Questions
                                                                                                                                              • Exercise 30 Else and If
                                                                                                                                                • What You Should See
                                                                                                                                                • Study Drills
                                                                                                                                                • Common Student Questions
                                                                                                                                                  • Exercise 31 Making Decisions
                                                                                                                                                    • What You Should See
                                                                                                                                                    • Study Drills
                                                                                                                                                    • Common Student Questions
                                                                                                                                                      • Exercise 32 Loops and Lists
                                                                                                                                                        • What You Should See
                                                                                                                                                        • Study Drills
                                                                                                                                                        • Common Student Questions
                                                                                                                                                          • Exercise 33 While Loops
                                                                                                                                                            • What You Should See
                                                                                                                                                            • Study Drills
                                                                                                                                                            • Common Student Questions
                                                                                                                                                              • Exercise 34 Accessing Elements of Lists
                                                                                                                                                                • Study Drills
                                                                                                                                                                  • Exercise 35 Branches and Functions
                                                                                                                                                                    • What You Should See
                                                                                                                                                                    • Study Drills
                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                      • Exercise 36 Designing and Debugging
                                                                                                                                                                        • Rules for if-statements
                                                                                                                                                                        • Rules for Loops
                                                                                                                                                                        • Tips for Debugging
                                                                                                                                                                        • Homework
                                                                                                                                                                          • Exercise 37 Symbol Review
                                                                                                                                                                            • Keywords
                                                                                                                                                                            • Data Types
                                                                                                                                                                            • String Escape Sequences
                                                                                                                                                                            • Old Style String Formats
                                                                                                                                                                            • Operators
                                                                                                                                                                            • Reading Code
                                                                                                                                                                            • Study Drills
                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                              • Exercise 38 Doing Things to Lists
                                                                                                                                                                                • What You Should See
                                                                                                                                                                                • What Lists Can Do
                                                                                                                                                                                • When to Use Lists
                                                                                                                                                                                • Study Drills
                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                  • Exercise 39 Dictionaries Oh Lovely Dictionaries
                                                                                                                                                                                    • A Dictionary Example
                                                                                                                                                                                    • What You Should See
                                                                                                                                                                                    • What Dictionaries Can Do
                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                      • Exercise 40 Modules Classes and Objects
                                                                                                                                                                                        • Modules Are Like Dictionaries
                                                                                                                                                                                          • Classes Are Like Modules
                                                                                                                                                                                          • Objects Are Like Import
                                                                                                                                                                                          • Getting Things from Things
                                                                                                                                                                                          • A First Class Example
                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                              • Exercise 41 Learning to Speak Object-Oriented
                                                                                                                                                                                                • Word Drills
                                                                                                                                                                                                • Phrase Drills
                                                                                                                                                                                                • Combined Drills
                                                                                                                                                                                                • A Reading Test
                                                                                                                                                                                                • Practice English to Code
                                                                                                                                                                                                • Reading More Code
                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                  • Exercise 42 Is-A Has-A Objects and Classes
                                                                                                                                                                                                    • How This Looks in Code
                                                                                                                                                                                                    • About class Name(object)
                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                      • Exercise 43 Basic Object-Oriented Analysis and Design
                                                                                                                                                                                                        • The Analysis of a Simple Game Engine
                                                                                                                                                                                                          • Write or Draw About the Problem
                                                                                                                                                                                                          • Extract Key Concepts and Research Them
                                                                                                                                                                                                          • Create a Class Hierarchy and Object Map for the Concepts
                                                                                                                                                                                                          • Code the Classes and a Test to Run Them
                                                                                                                                                                                                          • Repeat and Refine
                                                                                                                                                                                                            • Top Down versus Bottom Up
                                                                                                                                                                                                            • The Code for ldquoGothons from Planet Percal 25rdquo
                                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                                              • Exercise 44 Inheritance versus Composition
                                                                                                                                                                                                                • What Is Inheritance
                                                                                                                                                                                                                  • Implicit Inheritance
                                                                                                                                                                                                                  • Override Explicitly
                                                                                                                                                                                                                  • Alter Before or After
                                                                                                                                                                                                                  • All Three Combined
                                                                                                                                                                                                                    • The Reason for super()
                                                                                                                                                                                                                      • Using super() with __init__
                                                                                                                                                                                                                        • Composition
                                                                                                                                                                                                                        • When to Use Inheritance or Composition
                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                          • Exercise 45 You Make a Game
                                                                                                                                                                                                                            • Evaluating Your Game
                                                                                                                                                                                                                            • Function Style
                                                                                                                                                                                                                            • Class Style
                                                                                                                                                                                                                            • Code Style
                                                                                                                                                                                                                            • Good Comments
                                                                                                                                                                                                                            • Evaluate Your Game
                                                                                                                                                                                                                              • Exercise 46 A Project Skeleton
                                                                                                                                                                                                                                • macOSLinux Setup
                                                                                                                                                                                                                                • Windows 10 Setup
                                                                                                                                                                                                                                • Creating the Skeleton Project Directory
                                                                                                                                                                                                                                  • Final Directory Structure
                                                                                                                                                                                                                                    • Testing Your Setup
                                                                                                                                                                                                                                    • Using the Skeleton
                                                                                                                                                                                                                                    • Required Quiz
                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                      • Exercise 47 Automated Testing
                                                                                                                                                                                                                                        • Writing a Test Case
                                                                                                                                                                                                                                        • Testing Guidelines
                                                                                                                                                                                                                                        • What You Should See
                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                          • Exercise 48 Advanced User Input
                                                                                                                                                                                                                                            • Our Game Lexicon
                                                                                                                                                                                                                                              • Breaking Up a Sentence
                                                                                                                                                                                                                                              • Lexicon Tuples
                                                                                                                                                                                                                                              • Scanning Input
                                                                                                                                                                                                                                              • Exceptions and Numbers
                                                                                                                                                                                                                                                • A Test First Challenge
                                                                                                                                                                                                                                                • What You Should Test
                                                                                                                                                                                                                                                • Study Drills
                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                  • Exercise 49 Making Sentences
                                                                                                                                                                                                                                                    • Match and Peek
                                                                                                                                                                                                                                                    • The Sentence Grammar
                                                                                                                                                                                                                                                    • A Word on Exceptions
                                                                                                                                                                                                                                                    • The Parser Code
                                                                                                                                                                                                                                                    • Playing with the Parser
                                                                                                                                                                                                                                                    • What You Should Test
                                                                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                                      • Exercise 50 Your First Website
                                                                                                                                                                                                                                                        • Installing flask
                                                                                                                                                                                                                                                        • Make a Simple ldquoHello Worldrdquo Project
                                                                                                                                                                                                                                                        • Whatrsquos Going On
                                                                                                                                                                                                                                                        • Fixing Errors
                                                                                                                                                                                                                                                        • Create Basic Templates
                                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                                          • Exercise 51 Getting Input from a Browser
                                                                                                                                                                                                                                                            • How the Web Works
                                                                                                                                                                                                                                                            • How Forms Work
                                                                                                                                                                                                                                                            • Creating HTML Forms
                                                                                                                                                                                                                                                            • Creating a Layout Template
                                                                                                                                                                                                                                                            • Writing Automated Tests for Forms
                                                                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                                                                            • Breaking It
                                                                                                                                                                                                                                                              • Exercise 52 The Start of Your Web Game
                                                                                                                                                                                                                                                                • Refactoring the Exercise 43 Game
                                                                                                                                                                                                                                                                • Creating an Engine
                                                                                                                                                                                                                                                                • Your Final Exam
                                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                                  • Next Steps
                                                                                                                                                                                                                                                                    • How to Learn Any Programming Language
                                                                                                                                                                                                                                                                      • Advice from an Old Programmer
                                                                                                                                                                                                                                                                      • Appendix Command Line Crash Course
                                                                                                                                                                                                                                                                        • Introduction Shut Up and Shell
                                                                                                                                                                                                                                                                          • How to Use This Appendix
                                                                                                                                                                                                                                                                          • You Will Be Memorizing Things
                                                                                                                                                                                                                                                                            • The Setup
                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                • Paths Folders Directories (pwd)
                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                    • If You Get Lost
                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                        • Make a Directory (mkdir)
                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                            • Change Directory (cd)
                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                • List Directory (ls)
                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                    • Remove Directory (rmdir)
                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                        • Moving Around (pushd popd)
                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                            • Making Empty Files (touchNew-Item)
                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                • Copy a File (cp)
                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                    • Moving a File (mv)
                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                        • View a File (lessmore)
                                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                                            • Stream a File (cat)
                                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                                • Removing a File (rm)
                                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                                    • Exiting Your Terminal (exit)
                                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                                        • Command Line Next Steps
                                                                                                                                                                                                                                                                                                                                          • Unix Bash References
                                                                                                                                                                                                                                                                                                                                          • PowerShell References
                                                                                                                                                                                                                                                                                                                                              • Index
                                                                                                                                                                                                                                                                                                                                              • Code Snippets
Page 5: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code

StudyDrillsCommonStudentQuestions

Exercise3NumbersandMathWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise4VariablesandNamesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise5MoreVariablesandPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise6StringsandTextWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise7MorePrintingWhatYouShouldSeeStudyDrillsBreakItCommonStudentQuestions

Exercise8PrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise9PrintingPrintingPrintingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise10WhatWasThatWhatYouShouldSeeEscapeSequencesStudyDrillsCommonStudentQuestions

Exercise11AskingQuestionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise12PromptingPeopleWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise13ParametersUnpackingVariablesHoldUpFeaturesHaveAnotherNameWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise14PromptingandPassingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise15ReadingFilesWhatYouShouldSeeStudyDrills

CommonStudentQuestions

Exercise16ReadingandWritingFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise17MoreFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise18NamesVariablesCodeFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise19FunctionsandVariablesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise20FunctionsandFilesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise21FunctionsCanReturnSomethingWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise22WhatDoYouKnowSoFarWhatYouAreLearning

Exercise23StringsBytesandCharacterEncodings

InitialResearchSwitchesConventionsandEncodingsDisectingtheOutputDisectingtheCodeEncodingsDeepDiveBreakingIt

Exercise24MorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise25EvenMorePracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise26CongratulationsTakeaTestCommonStudentQuestions

Exercise27MemorizingLogicTheTruthTermsTheTruthTablesCommonStudentQuestions

Exercise28BooleanPracticeWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise29WhatIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise30ElseandIfWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise31MakingDecisionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise32LoopsandListsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise33WhileLoopsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise34AccessingElementsofListsStudyDrills

Exercise35BranchesandFunctionsWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise36DesigningandDebuggingRulesforif-statementsRulesforLoopsTipsforDebuggingHomework

Exercise37SymbolReview

KeywordsDataTypesStringEscapeSequencesOldStyleStringFormatsOperatorsReadingCodeStudyDrillsCommonStudentQuestions

Exercise38DoingThingstoListsWhatYouShouldSeeWhatListsCanDoWhentoUseListsStudyDrillsCommonStudentQuestions

Exercise39DictionariesOhLovelyDictionariesADictionaryExampleWhatYouShouldSeeWhatDictionariesCanDoStudyDrillsCommonStudentQuestions

Exercise40ModulesClassesandObjectsModulesAreLikeDictionaries

ClassesAreLikeModulesObjectsAreLikeImportGettingThingsfromThingsAFirstClassExample

WhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise41LearningtoSpeakObject-OrientedWordDrillsPhraseDrillsCombinedDrillsAReadingTestPracticeEnglishtoCodeReadingMoreCodeCommonStudentQuestions

Exercise42Is-AHas-AObjectsandClassesHowThisLooksinCodeAboutclassName(object)StudyDrillsCommonStudentQuestions

Exercise43BasicObject-OrientedAnalysisandDesignTheAnalysisofaSimpleGameEngine

WriteorDrawAbouttheProblemExtractKeyConceptsandResearchThemCreateaClassHierarchyandObjectMapfortheConceptsCodetheClassesandaTesttoRunThemRepeatandRefine

TopDownversusBottomUpTheCodeforldquoGothonsfromPlanetPercal25rdquoWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise44InheritanceversusCompositionWhatIsInheritance

ImplicitInheritanceOverrideExplicitlyAlterBeforeorAfter

AllThreeCombinedTheReasonforsuper()

Usingsuper()with__init__CompositionWhentoUseInheritanceorCompositionStudyDrillsCommonStudentQuestions

Exercise45YouMakeaGameEvaluatingYourGameFunctionStyleClassStyleCodeStyleGoodCommentsEvaluateYourGame

Exercise46AProjectSkeletonmacOSLinuxSetupWindows10SetupCreatingtheSkeletonProjectDirectory

FinalDirectoryStructureTestingYourSetupUsingtheSkeletonRequiredQuizCommonStudentQuestions

Exercise47AutomatedTestingWritingaTestCaseTestingGuidelinesWhatYouShouldSeeStudyDrillsCommonStudentQuestions

Exercise48AdvancedUserInputOurGameLexicon

BreakingUpaSentenceLexiconTuplesScanningInputExceptionsandNumbers

ATestFirstChallengeWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise49MakingSentencesMatchandPeekTheSentenceGrammarAWordonExceptionsTheParserCodePlayingwiththeParserWhatYouShouldTestStudyDrillsCommonStudentQuestions

Exercise50YourFirstWebsiteInstallingflaskMakeaSimpleldquoHelloWorldrdquoProjectWhatrsquosGoingOnFixingErrorsCreateBasicTemplatesStudyDrillsCommonStudentQuestions

Exercise51GettingInputfromaBrowserHowtheWebWorksHowFormsWork

CreatingHTMLFormsCreatingaLayoutTemplateWritingAutomatedTestsforFormsStudyDrillsBreakingIt

Exercise52TheStartofYourWebGameRefactoringtheExercise43GameCreatinganEngineYourFinalExamCommonStudentQuestions

NextStepsHowtoLearnAnyProgrammingLanguage

AdvicefromanOldProgrammer

AppendixCommandLineCrashCourseIntroductionShutUpandShell

HowtoUseThisAppendixYouWillBeMemorizingThings

TheSetupDoThisYouLearnedThisDoMore

PathsFoldersDirectories(pwd)DoThisYouLearnedThisDoMore

IfYouGetLostDoThisYouLearnedThis

MakeaDirectory(mkdir)DoThis

YouLearnedThisDoMore

ChangeDirectory(cd)DoThisYouLearnedThisDoMore

ListDirectory(ls)DoThisYouLearnedThisDoMore

RemoveDirectory(rmdir)DoThisYouLearnedThisDoMore

MovingAround(pushdpopd)DoThisYouLearnedThisDoMore

MakingEmptyFiles(touchNew-Item)DoThisYouLearnedThisDoMore

CopyaFile(cp)DoThisYouLearnedThisDoMore

MovingaFile(mv)DoThisYouLearnedThisDoMore

ViewaFile(lessmore)

DoThisYouLearnedThisDoMore

StreamaFile(cat)DoThisYouLearnedThisDoMore

RemovingaFile(rm)DoThisYouLearnedThisDoMore

ExitingYourTerminal(exit)DoThisYouLearnedThisDoMore

CommandLineNextStepsUnixBashReferencesPowerShellReferences

Index

Preface

ThissimplebookismeanttogetyoustartedinprogrammingThetitlesaysitrsquosthehardwaytolearntowritecodebutitrsquosactuallynotItrsquosonlytheldquohardrdquowaybecauseitusesatechniquecalledinstructionInstructioniswhereItellyoutodoasequenceofcontrolledexercisesdesignedtobuildaskillthroughrepetitionThistechniqueworksverywellwithbeginnerswhoknownothingandneedtoacquirebasicskillsbeforetheycanunderstandmorecomplextopicsItrsquosusedineverythingfrommartialartstomusictoevenbasicmathandreadingskillsThisbookinstructsyouinPythonbyslowlybuildingandestablishingskillsthroughtechniquessuchaspracticeandmemorizationthenapplyingthemtoincreasinglydifficultproblemsBytheendofthebookyouwillhavethetoolsneededtobeginlearningmorecomplexprogrammingtopicsIliketotellpeoplethatmybookgivesyouyourldquoprogrammingblackbeltrdquoWhatthismeansisthatyouknowthebasicswellenoughtonowstartlearningprogrammingIfyouworkhardtakeyourtimeandbuildtheseskillsyouwilllearntocode

ImprovementsinthePython3EditionLearnPython3theHardWaynowusesPython36IrsquovestandardizedonthisversionofPythonbecauseithasanewimprovedstringformattingsystemthatiseasiertousethantheprevious4(or3Iforgetthereweremany)versionsThereareafewproblemswithPython36forbeginnersbutIhelpyounavigatetheseissuesinthebookAparticularlyhairyproblemisthatPython36hasverypoorerrormessagesinsomekeyareasthatIhelpyouunderstandIhavealsoimprovedthevideosbasedonmyexperiencesoverthelastfiveyearsteachingpeoplePythonYoucanwatchthesevideosonlineatinformitcomtitle9780134692883InthepastthevideossimplyletyouwatchmedotheexerciseThePython3editionvideosalsoshowyouhowtobreakmdashandthenfixmdasheveryexerciseThisskilliscalledldquodebuggingrdquoItteachesyouhowtofixproblemsyourunintobutalsohowPythonrunstheprogramsyoursquorecreatingThegoalofthisnewmethodologyistobuildamentalmodelofhowPythonrunsyourcodesoyoucanmoreeasilyfigureoutwhyitrsquosbrokenYoursquollalsolearnmanyusefultricksfordebuggingbrokensoftwareLastthePython3editionfullysupportsMicrosoftWindows10frombeginningtoendThepreviouseditionfocusedmostlyontheUnix-stylesystemssuchasmacOSandLinuxwithWindowsbeingmoreofanafterthoughtAtthetimeIstartedwritingthePython3editionMicrosofthadstartedtotakeopensource

startedwritingthePython3editionMicrosofthadstartedtotakeopensourcetoolsanddevelopersseriouslyanditwasdifficulttoignorethemasaseriousPythondevelopmentplatformThevideosfeatureMicrosoftWindowsusingPythoninvariousscenariosandalsoshowmacOSandLinuxforfullcompatibilityItellyouaboutanygotchasoneachplatformcoverinstallationinstructionsandprovideanyothertipsIcangiveyou

TheHardWayIsEasierWiththehelpofthisbookyouwilldotheincrediblysimplethingsthatallprogrammersdotolearnaprogramminglanguage

1Gothrougheachexercise2Typeineachfileexactly3Makeitrun

ThatrsquositThiswillbeverydifficultatfirstbutstickwithitIfyougothroughthisbookanddoeachexerciseforoneortwohoursanightyouwillhaveagoodfoundationformovingontoanotherbookaboutPythontocontinueyourstudiesThisbookwonrsquotturnyouintoaprogrammerovernightbutitwillgetyoustartedonthepathtolearninghowtocodeThisbookrsquosjobistoteachyouthethreemostessentialskillsthatabeginningprogrammerneedstoknowreadingandwritingattentiontodetailandspottingdifferences

ReadingandWritingIfyouhaveaproblemtypingyouwillhaveaproblemlearningtocodeespeciallyifyouhaveaproblemtypingthefairlyoddcharactersinsourcecodeWithoutthissimpleskillyouwillbeunabletolearneventhemostbasicthingsabouthowsoftwareworksTypingthecodesamplesandgettingthemtorunwillhelpyoulearnthenamesofthesymbolsgetfamiliarwithtypingthemandgetyoureadingthelanguage

AttentiontoDetailTheoneskillthatseparatesgoodprogrammersfrombadprogrammersisattentiontodetailInfactitrsquoswhatseparatesthegoodfromthebadinanyprofessionYoumustpayattentiontothetiniestdetailsofyourworkoryouwillmissimportantelementsofwhatyoucreateInprogrammingthisishowyouendupwithbugsanddifficult-to-usesystemsBygoingthroughthisbookandcopyingeachexampleexactlyyouwillbetrainingyourbraintofocusonthedetailsofwhatyouaredoingasyouare

doingit

SpottingDifferencesAveryimportantskill(thatmostprogrammersdevelopovertime)istheabilitytovisuallynoticedifferencesbetweenthingsAnexperiencedprogrammercantaketwopiecesofcodethatareslightlydifferentandimmediatelystartpointingoutthedifferencesProgrammershaveinventedtoolstomakethiseveneasierbutwewonrsquotbeusinganyoftheseYoufirsthavetotrainyourbrainthehardwaythenusethetoolsWhileyoudotheseexercisestypingeachoneinyouwillmakemistakesItrsquosinevitableevenseasonedprogrammerswouldmakeafewYourjobistocomparewhatyouhavewrittentowhatrsquosrequiredandfixallthedifferencesBydoingsoyouwilltrainyourselftonoticemistakesbugsandotherproblems

AskDonrsquotStareIfyouwritecodeyouwillwritebugsAldquobugrdquomeansadefecterrororproblemwiththecodeyoursquovewrittenThelegendssaythatthiscomesfromanactualmoththatflewintooneofthefirstcomputerscausingittomalfunctionFixingitrequiredldquodebuggingrdquothecomputerIntheworldofsoftwaretherearealotofbugsSomanyLikethatfirstmothyourbugswillbehiddensomewhereinthecodeandyouhavetogofindthemYoucanrsquotjustsitatyourcomputerscreenstaringatthewordsyoursquovewrittenhopingthattheanswerjumpsoutatyouThereisnomoreadditionalinformationyoucangetdoingthatandyouneedadditionalinformationYouneedtogetupandgofindthemothTodothatyouhavetointerrogateyourcodeandaskitwhatisgoingonorlookattheproblemfromadifferentviewInthisbookIfrequentlytellyoutoldquostopstaringandaskrdquoIshowyouhowtomakeyourcodetellyoueverythingitcanaboutwhatrsquosgoingonandhowtoturnthisintopossiblesolutionsIalsoshowyouhowtoseeyourcodeindifferentwayssoyoucangetmoreinformationandinsight

DoNotCopy-PasteYoumusttypeeachoftheseexercisesinmanuallyIfyoucopy-pasteyoumightaswellnotevendothemThepointoftheseexercisesistotrainyourhandsyourbrainandyourmindinhowtoreadwriteandseecodeIfyoucopy-pasteyouarecheatingyourselfoutoftheeffectivenessofthelessons

UsingtheIncludedVideos

LearnPython3theHardWayhasanextensivesetofvideosdemonstratinghowthecodeworksandmostimportantlyhowtobreakitThevideosaretheperfectplacetodemonstratemanycommonerrorsbybreakingthePythoncodeonpurposeandshowingyouhowtofixitIalsowalkthroughthecodeusingdebuggingandinterrogationtricksandtechniquesThevideosarewhereIshowyouhowtoldquostopstaringandaskrdquothecodewhatrsquoswrongYoucanwatchthesevideosonlineatinformitcomtitle9780134692883

ANoteonPracticeandPersistenceWhileyouarestudyingprogrammingIrsquomstudyinghowtoplayguitarIpracticeiteverydayforatleasttwohoursadayIplayscaleschordsandarpeggiosforanhourandthenlearnmusictheoryeartrainingsongsandanythingelseIcanSomedaysIstudyguitarandmusicforeighthoursbecauseIfeellikeitanditrsquosfunTomerepetitivepracticeisnaturalandjusthowtolearnsomethingIknowthattogetgoodatanythingIhavetopracticeeverydayevenifIsuckthatday(whichisoften)oritrsquosdifficultKeeptryingandeventuallyitrsquollbeeasierandfunBetweenthetimethatIwroteLearnPythontheHardWayandLearnRubytheHardWayIdiscovereddrawingandpaintingIfellinlovewithmakingvisualartattheageof39andhavebeenspendingeverydaystudyingitinmuchthesamewaythatIstudiedguitarmusicandprogrammingIcollectedbooksofinstructionalmaterialdidwhatthebookssaidpaintedeverydayandfocusedonenjoyingtheprocessoflearningIambynomeansanldquoartistrdquooreventhatgoodbutIcannowsaythatIcandrawandpaintThesamemethodIrsquomteachingyouinthisbookappliedtomyadventuresinartIfyoubreaktheproblemdownintosmallexercisesandlessonsanddothemeverydayyoucanlearntodoalmostanythingIfyoufocusonslowlyimprovingandenjoyingthelearningprocessthenyouwillbenefitnomatterhowgoodyouareatitAsyoustudythisbookandcontinuewithprogrammingrememberthatanythingworthdoingisdifficultatfirstMaybeyouarethekindofpersonwhoisafraidoffailuresoyougiveupatthefirstsignofdifficultyMaybeyouneverlearnedself-disciplinesoyoucanrsquotdoanythingthatrsquosldquoboringrdquoMaybeyouweretoldthatyouareldquogiftedrdquosoyouneverattemptanythingthatmightmakeyouseemstupidornotaprodigyMaybeyouarecompetitiveandunfairlycompareyourselftosomeonelikemewhorsquosbeenprogrammingformorethan20yearsWhateveryourreasonforwantingtoquitkeepatitForceyourselfIfyourunintoaStudyDrillyoucanrsquotdooralessonyoujustdonotunderstandthenskip

itandcomebacktoitlaterJustkeepgoingbecausewithprogrammingtherersquosthisveryoddthingthathappensAtfirstyouwillnotunderstandanythingItrsquollbeweirdjustlikewithlearninganyhumanlanguageYouwillstrugglewithwordsandnotknowwhatsymbolsarewhatanditrsquollallbeveryconfusingThenonedayBANGmdashyourbrainwillsnapandyouwillsuddenlyldquogetitrdquoIfyoukeepdoingtheexercisesandkeeptryingtounderstandthemyouwillgetitYoumightnotbeamastercoderbutyouwillatleastunderstandhowprogrammingworksIfyougiveupyouwonrsquoteverreachthispointYouwillhitthefirstconfusingthing(whichiseverythingatfirst)andthenstopIfyoukeeptryingkeeptypingitinkeeptryingtounderstanditandreadingaboutityouwilleventuallygetitIfyougothroughthiswholebookandyoustilldonotunderstandhowtocodeatleastyougaveitashotYoucansayyoutriedyourbestandalittlemoreanditdidnrsquotworkoutbutatleastyoutriedYoucanbeproudofthat

RegisteryourcopyofLearnPython3theHardWayontheInformITsiteforconvenientaccesstoupdatesandcorrectionsastheybecomeavailableTostarttheregistrationprocessgotoinformitcomregisterandloginorcreateanaccountEntertheproductISBN(9780134692883)andanswerthesimpleproof-of-purchasequestionThenlookontheRegisteredProductstabforanAccessBonusContentlinknexttothisproductandfollowthatlinktoaccessthebonusmaterials

AcknowledgmentsIwouldliketothankAngelaforhelpingmewiththefirsttwoversionsofthisbookWithoutherIprobablywouldnrsquothavebotheredtofinishitatallShedidthecopyeditingofthefirstdraftandsupportedmeimmenselywhileIwroteitIrsquodalsoliketothankGregNewmanfordoingtheoriginalcoverartBrianShumateforearlywebsitedesignsandallofthepeoplewhoreadthisbookandtookthetimetosendmefeedbackandcorrectionsThankyou

Exercise0TheSetup

ThisexercisehasnocodeItissimplytheexerciseyoucompletetogetyourcomputertorunPythonYoushouldfollowtheseinstructionsasexactlyaspossibleIfyouhaveproblemsfollowingthewritteninstructionsthenwatchtheincludedvideosforyourplatform

WarningIfyoudonotknowhowtousePowerShellonWindowsTerminalonmacOSorbashonLinuxthenyouneedtogolearnthatfirstYoushoulddotheexercisesintheappendixfirstbeforecontinuingwiththeseexercises

macOSDothefollowingtaskstocompletethisexercise

1Gotohttpswwwpythonorgdownloadsreleasepython-360anddownloadtheversiontitledldquoMacOSX64-bit32-bitinstallerrdquoInstallitlikeyouwouldanyothersoftware

2GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3PutAtom(yourtexteditor)inyourdocksoyoucanreachiteasily4FindyourTerminalprogramSearchforitYouwillfindit5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthenameandhittingRETURN

8Typequit()Enterandgetoutofpython369YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryintheTerminal11LearnhowtochangeintoadirectoryintheTerminal12UseyoureditortocreateafileinthisdirectoryMakethefileSaveor

SaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindows14BackinTerminallistthedirectorywithlstoseeyournewlycreatedfile

macOSWhatYouShouldSeeHerersquosmedoingthisonmymacOScomputerinTerminalYourcomputermightbedifferentbutshouldbesimilartothisClickheretoviewcodeimage

$python36

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clangndash700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgt

~$mkdirlpthw

~$cdlpthw

lpthw$ls

Useyourtexteditorheretoedittesttxt

lpthw$ls

testtxt

lpthw$

Windows1GotohttpsatomiowithyourbrowsergettheAtomtexteditorandinstallitYoudonotneedtobetheadministratortodothis

2MakesureyoucangettoAtomeasilybyputtingitonyourdesktopandorinQuickLaunchBothoptionsareavailableduringsetupIfyoucannotrunAtombecauseyourcomputerisnotfastenoughthenseetheAlternativeTextEditorssectionattheendofthisexercise

3RunPowerShellfromtheStartmenuSearchforitandjustpressEntertorunit

4MakeashortcuttoitonyourdesktopandorQuickLaunchforyourconvenience

5RunyourPowerShellprogram(whichIwillcallTerminallater)Itwonrsquotlooklikemuch

6DownloadPython36fromhttpswwwpythonorgdownloadsreleasepython-360andinstallitBesuretochecktheboxthatsaystoaddPython36toyourpath

7InyourPowerShell(Terminal)programrunpythonYourunthingsinTerminalbyjusttypingthenameandpressingEnterIfyoutypepythonanditdoesnotrunthenyouhavetoreinstallPythonandmakesureyouchecktheboxforldquoAddpythontothePATHrdquoItrsquosverysmallsolookcarefully

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinthePowerShell(Terminal)11LearnhowtochangeintoadirectoryinthePowerShell(Terminal)12UseyoureditortocreateafileinthisdirectoryMakethefileSaveorSaveAsandpickthisdirectory

13GobacktoPowerShell(Terminal)usingjustthekeyboardtoswitchwindowsLookitupifyoucanrsquotfigureitout

14BackinPowerShell(Terminal)listthedirectorytoseeyournewlycreatedfile

FromnowonwhenIsayldquoTerminalrdquoorldquoshellrdquoImeanPowerShellandthatrsquoswhatyoushoulduseWhenIrunpython36youcanjusttypepython

WindowsWhatYouShouldSeeClickheretoviewcodeimage

gtpython

gtgtgtquit()

gtmkdirlpthw

gtcdlpthw

Hereyouwoulduseyourtexteditortomaketesttxtinlpthw

gt

gtdir

VolumeindriveCis

VolumeSerialNumberis085C-7E02

DirectoryofCDocumentsandSettingsyoulpthw

040520102332ltDIRgt

040520102332ltDIRgt

0405201023326testtxt

1File(s)6bytes

2Dir(s)14804623360bytesfree

gt

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

LinuxLinuxisavariedoperatingsystemwithmanydifferentwaystoinstallsoftwareIrsquomassumingifyouarerunningLinuxthenyouknowhowtoinstallpackagessohereareyourinstructions

1UseyourpackagemanagertoinstallPython36andifyoucanrsquotthendownloadsourcefromhttpswwwpythonorgdownloadsreleasepython-360andbuildfromsource

2UseyourLinuxpackagemanagerandinstalltheAtomtexteditorIfAtomdoesnotsuityouthenseetheAlternativeTextEditorssectionattheendofthisexercise

3MakesureyoucangettoAtomeasilybyputtingitinyourwindowmanagerrsquosmenu

4FindyourTerminalprogramItcouldbecalledGNOMETerminalKonsoleorxterm

5PutyourTerminalinyourdockaswell6RunyourTerminalprogramItwonrsquotlooklikemuch7InyourTerminalprogramrunpython36YourunthingsinTerminalbyjusttypingthecommandnameandpressingEnterIfyoucanrsquotrunpython36tryrunningjustpython

8Typequit()andpressEntertoexitpython9YoushouldbebackatapromptsimilartowhatyouhadbeforeyoutypedpythonIfnotfindoutwhy

10LearnhowtomakeadirectoryinTerminal11LearnhowtochangeintoadirectoryinTerminal12UseyoureditortocreateafileinthisdirectoryTypicallyyouwillmake

thefileSaveorSaveAsandpickthisdirectory13GobacktoTerminalusingjustthekeyboardtoswitchwindowsLookit

upifyoucanrsquotfigureitout14BackinTerminallistthedirectorytoseeyournewlycreatedfile

LinuxWhatYouShouldSee

Clickheretoviewcodeimage

$python

gtgtgtquit()

$mkdirlpthw

$cdlpthw

Useyourtexteditorheretoedittesttxt

$ls

testtxt

$

Itisstillcorrectifyouseedifferentinformationthanminebutyoursshouldbesimilar

FindingThingsontheInternetAmajorpartofthisbookislearningtoresearchprogrammingtopicsonlineIrsquolltellyoutoldquosearchforthisontheinternetrdquoandyourjobistouseasearchenginetofindtheanswerThereasonIhaveyousearchinsteadofjustgivingyoutheanswerisbecauseIwantyoutobeanindependentlearnerwhodoesnotneedmybookwhenyoursquoredonewithitIfyoucanfindtheanswerstoyourquestionsonlinethenyouareonestepclosertonotneedingmeandthatismygoalThankstosearchenginessuchasGoogleyoucaneasilyfindanythingItellyoutofindIfIsayldquosearchonlineforthepythonlistfunctionsrdquothenyousimplydothis

1Gotohttpgooglecom2Typepython3listfunctions3Readthewebsiteslistedtofindthebestanswer

WarningsforBeginnersYouaredonewiththisexerciseThisexercisemightbehardforyoudependingonyourfamiliaritywithyourcomputerIfitisdifficulttakethetimetoreadandstudyandgetthroughitbecauseuntilyoucandotheseverybasicthingsyouwillfinditdifficulttogetmuchprogrammingdoneIfsomeonetellsyoutostopataspecificexerciseinthisbookortoskipcertainonesyoushouldignorethatpersonAnyonetryingtohideknowledgefromyouorworsemakeyougetitfromtheminsteadofthroughyourowneffortsistryingtomakeyoudependonthemforyourskillsDonrsquotlistentothemanddotheexercisesanywaysothatyoulearnhowtoeducateyourselfAprogrammerwilleventuallytellyoutousemacOSorLinuxIftheprogrammerlikesfontsandtypographytheyrsquolltellyoutogetamacOScomputerIfhelikescontrolandhasahugebeardhewill(orzewillifyou

computerIfhelikescontrolandhasahugebeardhewill(orzewillifyouprefernon-genderedpronounsforhumanswithbeards)tellyoutoinstallLinuxAgainusewhatevercomputeryouhaverightnowthatworksAllyouneedisaneditoraTerminalandPythonFinallythepurposeofthissetuphelpsyoudothreethingsveryreliablywhileyouworkontheexercises

1Writeexercisesusingthetexteditor2Runtheexercisesyouwrote3Fixthemwhentheyarebroken4Repeat

Anythingelsewillonlyconfuseyousosticktotheplan

AlternativeTextEditorsTexteditorsareveryimportanttoaprogrammerbutasabeginneryouonlyneedasimpleprogrammerrsquostexteditorThesearedifferentfromsoftwareforwritingstoriesandbooksbecausetheyworkwiththeuniqueneedsofcomputercodeIrecommendAtominthisbookbecauseitisfreeandworksnearlyeverywhereHoweverAtommaynotrunwellonyourcomputersoherearesomealternativestotry

ThesearerankedinorderofmostlikelytoworkKeepinmindthattheseprojectsmaybeabandoneddeadornotworkanymoreonyourcomputerIfyoutryoneanditdoesnrsquotworktryanotheroneIrsquovealsolistedtheldquoWorksOnrdquoinorderofmostlikelytoworksoifyoursquoreonWindowsthenlookattheeditorswhereWindowsislistedfirstintheldquoWorksOnrdquocolumnIfyoualreadyknowhowtouseVimorEmacsthenfeelfreetousethemIfyouhaveneverusedVimorEmacsthenavoidthemProgrammersmaytrytoconvinceyoutouseVimorEmacsbutthiswillonlyderailyouYourfocusislearningPythonnotlearningVimorEmacsIfyoutrytouseVimanddonrsquotknowhowtoquitthentypeqorZZIfsomeonetoldyoutouseVimand

theydidnrsquoteventellyouthisthennowyouknowwhyyoushouldnrsquotlistentothemDonotuseanIntegratedDevelopmentEnvironment(IDE)whileyougothroughthisbookRelyingonanIDEmeansthatyoucanrsquotworkwithnewprogramminglanguagesuntilsomecompanydecidestosellyouanIDEforthatlanguageThismeansyoucanrsquotusethatnewlanguageuntilthelanguageislargeenoughtojustifyalucrativecustomerbaseIfyouareconfidentyoucanworkwithonlyaprogrammerrsquostexteditor(likeVimEmacsAtometc)thenyoudonrsquothavetowaitforathirdpartyIDEsareniceinsomesituations(suchasworkingwithagiantexistingcodebase)butbeingaddictedtothemwilllimityourfutureYoushouldalsonotuseIDLEIthasseriouslimitationsinhowitworksandisnrsquotaverygoodpieceofsoftwareAllyouneedisasimpletexteditorashellandPython

Exercise1AGoodFirstProgram

WarningIfyouskippedExercise0thenyouarenotdoingthisbookrightAreyoutryingtouseIDLEoranIDEIsaidnottouseoneinExercise0soyoushouldnotuseoneIfyouskippedExercise0pleasegobacktoitandreadit

YoushouldhavespentagoodamountoftimeinExercise0learninghowtoinstallatexteditorrunthetexteditorruntheTerminalandworkwithbothofthemIfyouhavenrsquotdonethatthendonotgoonYouwillnothaveagoodtimeThisistheonlytimeIrsquollstartanexercisewithawarningthatyoushouldnotskiporgetaheadofyourselfTypethefollowingtextintoasinglefilenamedex1pyPythonworksbestwithfilesendinginpyClickheretoviewcodeimage

ex1py

1print(HelloWorld)

2print(HelloAgain)

3print(Iliketypingthis)

4print(Thisisfun)

5print(YayPrinting)

6print(Idmuchratheryounot)

7print(Isaiddonottouchthis)

YourAtomtexteditorshouldlooksomethinglikethisonallplatforms

DonrsquotworryifyoureditordoesnrsquotlookexactlythesameitshouldbeclosethoughYoumayhaveaslightlydifferentwindowheadermaybeslightlydifferentcolorsandtheleftsideofyourAtomwindowwonrsquotsayldquozedshawrdquobutwillinsteadshowthedirectoryyouusedforsavingyourfilesAllofthosedifferencesarefineWhenyoucreatethisfilekeepinmindthesepoints

1IdidnottypethelinenumbersontheleftThoseareprintedinthebooksoIcantalkaboutspecificlinesbysayingldquoSeeline5rdquoYoudonottypelinenumbersintoPythonscripts

2IhavetheprintatthebeginningofthelineanditlooksexactlythesameaswhatIhaveinex1pyExactlymeansexactlynotkindofsortofthesameEverysinglecharacterhastomatchforittoworkColordoesnrsquot

matteronlythecharactersyoutypeInmacOSTerminalor(maybe)Linuxrunthefilebytyping

python36ex1py

OnWindowsrememberyoualwaystypepythoninsteadofpython36likethis

pythonex1py

IfyoudiditrightthenyoushouldseethesameoutputasIintheWhatYouShouldSeesectionofthisexerciseIfnotyouhavedonesomethingwrongNothecomputerisnotwrong

WhatYouShouldSeeOnmacOSintheTerminalyoushouldseethis

OnWindowsinPowerShellyoushouldseethis

Youmayseedifferentnamesbeforethepython36ex1pycommandbuttheimportantpartisthatyoutypethecommandandseetheoutputisthesameasmineIfyouhaveanerroritwilllooklikethisClickheretoviewcodeimage

$python36pythonex1py

Filepythonex1pyline3

print(Iliketypingthis

^

SyntaxErrorEOLwhilescanningstringliteral

ItrsquosimportantthatyoucanreadtheseerrormessagesbecauseyouwillbemakingmanyofthesemistakesEvenImakemanyofthesemistakesLetrsquoslookatthislinebyline

1WeranourcommandintheTerminaltoruntheex1pyscript2Pythontellsusthatthefileex1pyhasanerroronline3ofex1py3Itprintsthislineofcodeforustoseeit4Thenitputsa^(caret)charactertopointatwheretheproblemisNoticethemissing(double-quote)character

5FinallyitprintsoutaldquoSyntaxErrorrdquoandtellsussomethingaboutwhatmightbetheerrorUsuallytheseareverycrypticbutifyoucopythattext

mightbetheerrorUsuallytheseareverycrypticbutifyoucopythattextintoasearchengineyouwillfindsomeoneelsewhorsquoshadthaterrorandyoucanprobablyfigureouthowtofixit

StudyDrillsTheStudyDrillscontainthingsyoushouldtrytodoIfyoucanrsquotskipitandcomebacklaterForthisexercisetrythesethings

1Makeyourscriptprintanotherline2Makeyourscriptprintonlyoneofthelines3Puta(octothorpe)characteratthebeginningofalineWhatdiditdoTrytofindoutwhatthischaracterdoes

FromnowonIwonrsquotexplainhoweachexerciseworksunlessanexerciseisdifferent

WarningAnldquooctothorperdquoisalsocalledaldquopoundrdquoldquohashrdquoldquomeshrdquooranynumberofothernamesPicktheonethatmakesyouchillout

CommonStudentQuestionsTheseareactualquestionsthatrealstudentshaveaskedwhendoingthisexercise

CanIuseIDLENoyoushoulduseTerminalonmacOSandPowerShellonWindowsjustlikeIhavehereIfyoudonrsquotknowhowtousethosethenyoucangoreadtheappendix

HowdoyougetcolorsinyoureditorSaveyourfilefirstasapyfilesuchasex1pyThenyoursquollhavecolorwhenyoutype

IgetSyntaxErrorinvalidsyntaxwhenIrunex1pyYouareprobablytryingtorunPythonthentryingtotypePythonagainCloseyourTerminalstartitagainandrightawaytypeonlypython36ex1py

Igetcantopenfileex1py[Errno2]NosuchfileordirectoryYouneedtobeinthesamedirectoryasthefileyoucreatedMakesureyouusethecdcommandtogotherefirstForexampleifyousavedyourfileinlpthwex1pythenyouwoulddocdlpthwbeforetryingtorunpython36

ex1pyIfyoudonrsquotknowwhatanyofthatmeansthengothroughtheappendix

MyfiledoesnrsquotrunIjustgetthepromptbackwithnooutputYoumostlikelytookthecodeinmyex1pyfileliterallyandthoughtthatprint(HelloWorld)meanttotypeonlyHelloWorldintothefilewithouttheprintYourfilehastobeexactlylikemine

Exercise2CommentsandPoundCharacters

CommentsareveryimportantinyourprogramsTheyareusedtotellyouwhatsomethingdoesinEnglishandtheyareusedtodisablepartsofyourprogramifyouneedtoremovethemtemporarilyHerersquoshowyouusecommentsinPythonClickheretoviewcodeimage

ex2py

1Acommentthisissoyoucanreadyourprogramlater

2Anythingaftertheisignoredbypython

3

4print(Icouldhavecodelikethis)andthecommentafteris

ignored

5

6Youcanalsouseacommenttodisableorcommentoutcode

7print(Thiswontrun)

8

9print(Thiswillrun)

FromnowonIrsquomgoingtowritecodelikethisItisimportantforyoutounderstandthateverythingdoesnothavetobeliteralYourscreenandprogrammayvisuallylookdifferentbutwhatrsquosimportantisthetextyoutypeintothefileyoursquorewritinginyourtexteditorInfactIcouldworkwithanytexteditorandtheresultswouldbethesame

WhatYouShouldSee

Exercise2Session

$python36ex2py

Icouldhavecodelikethis

Thiswillrun

AgainIrsquomnotgoingtoshowyouscreenshotsofalltheTerminalspossibleYoushouldunderstandthattheprecedingisnotaliteraltranslationofwhatyouroutputshouldlooklikevisuallybutthetextbetweenthefirst$python36andlast$lineswillbewhatyoufocuson

StudyDrills

1Findoutifyouwererightaboutwhatthecharacterdoesandmakesureyouknowwhatitrsquoscalled(octothorpeorpoundcharacter)

2Takeyourex2pyfileandrevieweachlinegoingbackwardStartatthelastlineandcheckeachwordinreverseagainstwhatyoushouldhavetyped

3DidyoufindmoremistakesFixthem4ReadwhatyoutypedaboveoutloudincludingsayingeachcharacterbyitsnameDidyoufindmoremistakesFixthem

CommonStudentQuestionsAreyousureiscalledthepoundcharacterIcallittheoctothorpebecausethatistheonlynamethatnoonecountryusesandthatworksineverycountryEverycountrythinksitsnameforthisonecharacterisboththemostimportantwaytodoitandtheonlywayitrsquosdoneTomethisissimplyarroganceandreallyyrsquoallshouldjustchilloutandfocusonmoreimportantthingslikelearningtocode

Whydoestheinprint(Hithere)notgetignoredTheinthatcodeisinsideastringsoitwillbeputintothestringuntiltheendingcharacterishitPoundcharactersinstringsarejustconsideredcharactersnotcomments

HowdoIcommentoutmultiplelinesPutainfrontofeachoneIcanrsquotfigureouthowtotypeacharacteronmycountryrsquoskeyboardHowdoIdothatSomecountriesusetheALTkeyandcombinationsofotherkeystoprintcharactersforeigntotheirlanguageYoursquollhavetolookonlineinasearchenginetoseehowtotypeit

WhydoIhavetoreadcodebackwardItrsquosatricktomakeyourbrainnotattachmeaningtoeachpartofthecodeanddoingthatmakesyouprocesseachpieceexactlyThisisahandyerror-checkingtechnique

Exercise3NumbersandMath

EveryprogramminglanguagehassomekindofwayofdoingnumbersandmathDonotworryprogrammersfrequentlylieaboutbeingmathgeniuseswhentheyreallyarenrsquotIftheyweremathgeniusestheywouldbedoingmathnotwritingbuggywebframeworkssotheycandriveracecarsThisexercisehaslotsofmathsymbolsLetrsquosnamethemrightawaysoyouknowwhattheyarecalledAsyoutypethisoneinsaythenameWhensayingthemfeelsboringyoucanstopsayingthemHerearethenamesbull+plusbull-minusbullslashbullasteriskbullpercentbullltless-thanbullgtgreater-thanbulllt=less-than-equalbullgt=greater-than-equalNoticehowtheoperationsaremissingAfteryoutypeinthecodeforthisexercisegobackandfigureoutwhateachofthesedoesandcompletethetableForexample+doesadditionClickheretoviewcodeimage

ex3py

1print(Iwillnowcountmychickens)

2

3print(Hens25+306)

4print(Roosters100-2534)

5

6print(NowIwillcounttheeggs)

7

8print(3+2+1-5+42-14+6)

9

10print(Isittruethat3+2lt5-7)

11

12print(3+2lt5-7)

13

14print(Whatis3+23+2)

15print(Whatis5-75-7)

16

17print(OhthatswhyitsFalse)

18

19print(Howaboutsomemore)

20

21print(Isitgreater5gt-2)

22print(Isitgreaterorequal5gt=-2)

23print(Isitlessorequal5lt=-2)Makesureyoutypethis

exactlybeforeyourunitCompareeachlineofyourfiletomyfile

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise3Session

$python36ex3py

Iwillnowcountmychickens

Hens300

Roosters97

NowIwillcounttheeggs

675

Isittruethat3+2lt5-7

False

Whatis3+25

Whatis5-7-2

OhthatswhyitsFalse

Howaboutsomemore

IsitgreaterTrue

IsitgreaterorequalTrue

IsitlessorequalFalse

StudyDrills1Aboveeachlineusethetowriteacommenttoyourselfexplainingwhatthelinedoes

2RememberinExercise0whenyoustartedpython36Startpython36thiswayagainandusingthemathoperatorsusePythonasacalculator

3Findsomethingyouneedtocalculateandwriteanewpyfilethatdoesit

4Rewriteex3pytousefloatingpointnumberssoitrsquosmoreaccurate200isfloatingpoint

CommonStudentQuestionsWhyisthecharacteraldquomodulusrdquoandnotaldquopercentrdquoMostlythatrsquosjusthowthedesignerschosetousethatsymbolInnormalwritingyouarecorrecttoreaditasaldquopercentrdquoInprogrammingthiscalculationistypicallydonewithsimpledivisionandtheoperatorThemodulusisadifferentoperationthatjusthappenstousethesymbol

HowdoesworkAnotherwaytosayitisldquoXdividedbyYwithJ

remainingrdquoForexampleldquo100dividedby16with4remainingrdquoTheresultofistheJpartortheremainingpart

WhatistheorderofoperationsIntheUnitedStatesweuseanacronymcalledPEMDASwhichstandsforParenthesesExponentsMultiplicationDivisionAdditionSubtractionThatrsquostheorderPythonfollowsaswellThemistakepeoplemakewithPEMDASistothinkthisisastrictorderasinldquoDoPthenEthenMthenDthenAthenSrdquoTheactualorderisyoudothemultiplicationanddivision(MampD)inonestepfromlefttorightthenyoudotheadditionandsubtractioninonestepfromlefttorightSoyoucouldrewritePEMDASasPE(MampD)(AampS)

Exercise4VariablesandNames

NowyoucanprintthingswithprintandyoucandomathThenextstepistolearnaboutvariablesInprogrammingavariableisnothingmorethananameforsomethingsimilartohowmynameldquoZedrdquoisanameforldquothehumanwhowrotethisbookrdquoProgrammersusethesevariablenamestomaketheircodereadmorelikeEnglishandbecausetheyhavelousymemoriesIftheydidnrsquotusegoodnamesforthingsintheirsoftwaretheyrsquodgetlostwhentheytriedtoreadtheircodeagainIfyougetstuckwiththisexerciserememberthetricksyouhavebeentaughtsofaroffindingdifferencesandfocusingondetails1WriteacommentaboveeachlineexplainingtoyourselfinEnglishwhatitdoes

2Readyourpyfilebackward3Readyourpyfileoutloudsayingeventhecharacters

Clickheretoviewcodeimage

ex4py

1cars=100

2space_in_a_car=40

3drivers=30

4passengers=90

5cars_not_driven=cars-drivers

6cars_driven=drivers

7carpool_capacity=cars_drivenspace_in_a_car

8average_passengers_per_car=passengerscars_driven

9

10

11print(Therearecarscarsavailable)

12print(Thereareonlydriversdriversavailable)

13print(Therewillbecars_not_drivenemptycarstoday)

14print(Wecantransportcarpool_capacitypeopletoday)

15print(Wehavepassengerstocarpooltoday)

16print(Weneedtoputaboutaverage_passengers_per_car

17ineachcar)

WarningThe_inspace_in_a_cariscalledanunderscorecharacterFindouthowtotypeitifyoudonotalreadyknowWeusethischaracteralotto

putanimaginaryspacebetweenwordsinvariablenames

WhatYouShouldSeeClickheretoviewcodeimage

Exercise4Session

$python36ex4py

Thereare100carsavailable

Thereareonly30driversavailable

Therewillbe70emptycarstoday

Wecantransport1200peopletoday

Wehave90tocarpooltoday

Weneedtoputabout30ineachcar

StudyDrillsWhenIwrotethisprogramthefirsttimeIhadamistakeandPythontoldmeaboutitlikethisClickheretoviewcodeimage

Traceback(mostrecentcalllast)

Fileex4pyline8inltmodulegt

average_passengers_per_car=car_pool_capacitypassenger

NameErrornamecar_pool_capacityisnotdefined

ExplainthiserrorinyourownwordsMakesureyouuselinenumbersandexplainwhyHerearemorestudydrills1Iused40forspace_in_a_carbutisthatnecessaryWhathappensifitrsquosjust4

2Rememberthat40isafloatingpointnumberItrsquosjustanumberwithadecimalpointandyouneed40insteadofjust4sothatitisfloatingpoint

3Writecommentsaboveeachofthevariableassignments4Makesureyouknowwhat=iscalled(equals)andthatitspurposeistogivedata(numbersstringsetc)names(cars_drivenpassengers)

5Rememberthat_isanunderscorecharacter6Tryrunningpython36fromtheTerminalasacalculatorlikeyoudidbeforeandusevariablenamestodoyourcalculationsPopularvariablenamesincludeixandj

CommonStudentQuestions

CommonStudentQuestionsWhatisthedifferencebetween=(single-equal)and==(double-equal)The=(single-equal)assignsthevalueontherighttoavariableontheleftThe==(double-equal)testswhethertwothingshavethesamevalueYoursquolllearnaboutthisinExercise27

Canwewritex=100insteadofx=100YoucanbutitrsquosbadformYoushouldaddspacearoundoperatorslikethissothatitrsquoseasiertoread

WhatdoyoumeanbyldquoreadthefilebackwardrdquoVerysimpleImagineyouhaveafilewith16linesofcodeinitStartatline16andcompareittomyfileatline16Thendoitagainfor15andsoonuntilyoursquovereadthewholefilebackward

Whydidyouuse40forspace_in_a_carItismostlysoyoucanthenfindoutwhatafloatingpointnumberisandaskthisquestionSeetheStudyDrills

Exercise5MoreVariablesandPrinting

NowwersquolldoevenmoretypingofvariablesandprintingthemoutThistimewersquollusesomethingcalledaformatstringEverytimeyouput(double-quotes)aroundapieceoftextyouhavebeenmakingastringAstringishowyoumakesomethingthatyourprogrammightgivetoahumanYouprintstringssavestringstofilessendstringstowebserversamongmanyotherthingsStringsarereallyhandysointhisexerciseyouwilllearnhowtomakestringsthathavevariablesembeddedinthemYouembedvariablesinsideastringbyusingaspecialsequenceandthenputthevariableyouwantinsidethecharactersYoualsomuststartthestringwiththeletterfforldquoformatrdquoasinfHellosomevarThislittlefbeforethe(double-quote)andthecharacterstellPython3ldquoHeythisstringneedstobeformattedPutthesevariablesinthererdquoAsusualjusttypethisinevenifyoudonotunderstanditandmakeitexactlythesameClickheretoviewcodeimage

ex5py

1my_name=ZedAShaw

2my_age=35notalie

3my_height=74inches

4my_weight=180lbs

5my_eyes=Blue

6my_teeth=White

7my_hair=Brown

8

9print(fLetstalkaboutmy_name)

10print(fHesmy_heightinchestall)

11print(fHesmy_weightpoundsheavy)

12print(Actuallythatsnottooheavy)

13print(fHesgotmy_eyeseyesandmy_hairhair)

14print(fHisteethareusuallymy_teethdependingonthe

coffee)

15

16thislineistrickytrytogetitexactlyright

17total=my_age+my_height+my_weight

18print(fIfIaddmy_agemy_heightandmy_weightIget

total)

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Exercise5Session

$python36ex5py

LetstalkaboutZedAShaw

Hes74inchestall

Hes180poundsheavy

Actuallythatsnottooheavy

HesgotBlueeyesandBrownhair

HisteethareusuallyWhitedependingonthecoffee

IfIadd3574and180Iget289

StudyDrills1Changeallthevariablessothereisnomy_infrontofeachoneMakesureyouchangethenameeverywherenotjustwhereyouused=tosetthem

2TrytowritesomevariablesthatconverttheinchesandpoundstocentimetersandkilogramsDonotjusttypeinthemeasurementsWorkoutthemathinPython

CommonStudentQuestionsCanImakeavariablelikethis1=ZedShawNo1isnotavalidvariablenameTheyneedtostartwithacharactersoa1wouldworkbut1willnot

HowcanIroundafloatingpointnumberYoucanusetheround()functionlikethisround(17333)

WhydoesthisnotmakesensetomeTrymakingthenumbersinthisscriptyourmeasurementsItrsquosweirdbuttalkingaboutyourselfwillmakeitseemmorerealAlsoyoursquorejuststartingoutsoitwonrsquotmaketoomuchsenseKeepgoingandmoreexerciseswillexplainitmore

Exercise6StringsandText

WhileyouhavebeenwritingstringsyoustilldonotknowwhattheydoInthisexercisewecreateabunchofvariableswithcomplexstringssoyoucanseewhattheyareforFirstanexplanationofstringsAstringisusuallyabitoftextyouwanttodisplaytosomeoneorldquoexportrdquooutoftheprogramyouarewritingPythonknowsyouwantsomethingtobeastringwhenyouputeither(double-quotes)or(single-quotes)aroundthetextYousawthismanytimeswithyouruseofprintwhenyouputthetextyouwanttogoinsidethestringinsideoraftertheprinttoprintthestringStringscancontainanynumberofvariablesthatareinyourPythonscriptRememberthatavariableisanylineofcodewhereyousetaname=(equal)toavalueInthecodeforthisexercisetypes_of_people=10createsavariablenamedtypes_of_peopleandsetsit=(equal)to10Youcanputthatinanystringwithtypes_of_peopleYoualsoseethatIhavetouseaspecialtypeofstringtoldquoformatrdquoitrsquoscalledanldquof-stringrdquoandlookslikethisClickheretoviewcodeimage

fsomestuffhereavariable

fsomeotherstuffanothervar

Pythonalsohasanotherkindofformattingusingtheformat()syntaxwhichyouseeonline17YoursquollseemeusethatsometimeswhenIwanttoapplyaformattoanalready-createdstringsuchasinaloopWersquollcoverthatmorelaterWewillnowtypeinawholebunchofstringsvariablesandformatsandprintthemWewillalsopracticeusingshortabbreviatedvariablenamesProgrammerslovesavingtimeatyourexpensebyusingannoyinglyshortandcrypticvariablenamessoletrsquosgetyoustartedreadingandwritingthemearlyonClickheretoviewcodeimage

ex6py

1types_of_people=10

2x=fTherearetypes_of_peopletypesofpeople

3

4binary=binary

5do_not=dont

6y=fThosewhoknowbinaryandthosewhodo_not

7

8print(x)

9print(y)

10

11print(fIsaidx)

12print(fIalsosaidy)

13

14hilarious=False

15joke_evaluation=Isntthatjokesofunny

16

17print(joke_evaluationformat(hilarious))

18

19w=Thisistheleftsideof

20e=astringwitharightside

21

22print(w+e)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise6Session

$python36ex6py

Thereare10typesofpeople

Thosewhoknowbinaryandthosewhodont

IsaidThereare10typesofpeople

IalsosaidThosewhoknowbinaryandthosewhodont

IsntthatjokesofunnyFalse

Thisistheleftsideofastringwitharightside

StudyDrills1Gothroughthisprogramandwriteacommentaboveeachlineexplainingit

2FindalltheplaceswhereastringisputinsideastringTherearefourplaces

3AreyousurethereareonlyfourplacesHowdoyouknowMaybeIlikelying

4Explainwhyaddingthetwostringswandewith+makesalongerstring

BreakIt

YouarenowatapointwhereyoucantrytobreakyourcodetoseewhathappensThinkofthisasagametodevisethemostcleverwaytobreakthecodeYoucanalsofindthesimplestwaytobreakitOnceyoubreakthecodeyouthenneedtofixitIfyouhaveafriendthenthetwoofyoucantrytobreakeachotherrsquoscodeandfixitGiveyourfriendyourex6pyfilesotheycanbreaksomethingThenyoutrytofindtheirerrorandfixitHavefunwiththisandrememberthatifyouwrotethiscodeonceyoucandoitagainIfyoutakeyourdamagetoofaryoucanalwaystypeitinagainforextrapractice

CommonStudentQuestionsWhydoyouput(single-quotes)aroundsomestringsandnotothersMostlyitrsquosbecauseofstylebutIrsquolluseasingle-quoteinsideastringthathasdouble-quotesLookatlines6and15toseehowIrsquomdoingthat

Ifyouthoughtthejokewasfunnycouldyouwritehilarious=TrueYesandyoursquolllearnmoreaboutthesebooleanvaluesinExercise27

Exercise7MorePrinting

NowwearegoingtodoabunchofexerciseswhereyoujusttypecodeinandmakeitrunIwonrsquotbeexplainingthisexercisebecauseitismoreofthesameThepurposeistobuildupyourchopsSeeyouinafewexercisesanddonotskipDonotpasteClickheretoviewcodeimage

ex7py

1print(Maryhadalittlelamb)

2print(Itsfleecewaswhiteasformat(snow))

3print(AndeverywherethatMarywent)

4print(10)whatdthatdo

5

6end1=C

7end2=h

8end3=e

9end4=e

10end5=s

11end6=e

12end7=B

13end8=u

14end9=r

15end10=g

16end11=e

17end12=r

18

19watchthatcommaattheendtryremovingittoseewhat

happens

20print(end1+end2+end3+end4+end5+end6end=)

21print(end7+end8+end9+end10+end11+end12)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise7Session

$python36ex7py

Maryhadalittlelamb

Itsfleecewaswhiteassnow

AndeverywherethatMarywent

CheeseBurger

StudyDrillsForthesenextfewexercisesyouwillhavetheexactsameStudyDrills

1Gobackthroughandwriteacommentonwhateachlinedoes2Readeachonebackwardoroutloudtofindyourerrors3Fromnowonwhenyoumakemistakeswritedownonapieceofpaperwhatkindofmistakeyoumade

4Whenyougotothenextexerciselookatthemistakesyouhavemadeandtrynottomaketheminthisnewone

5RememberthateveryonemakesmistakesProgrammersarelikemagicianswhofooleveryoneintothinkingtheyareperfectandneverwrongbutitrsquosallanactTheymakemistakesallthetime

BreakItDidyouhavefunbreakingthecodeinExercise6FromnowonyoursquoregoingtobreakallthecodeyouwriteorafriendrsquoscodeIwonrsquothaveaBreakItsectionexplicitlyineveryexercisebutIwilldothisinalmosteveryvideoYourgoalistofindasmanydifferentwaystobreakyourcodeuntilyougettiredorexhaustallpossibilitiesInsomeexercisesImightpointoutaspecificcommonwaypeoplebreakthatexercisersquoscodebutotherwiseconsiderthisastandingordertoalwaysbreakit

CommonStudentQuestionsWhyareyouusingthevariablenamedsnowThatrsquosactuallynotavariableitisjustastringwiththewordsnowinitAvariablewouldnrsquothavethesingle-quotesaroundit

IsitnormaltowriteanEnglishcommentforeverylineofcodelikeyousaytodoinStudyDrill1Noyouwritecommentsonlytoexplaindifficult-to-understandcodeorwhyyoudidsomethingWhyisusuallymuchmoreimportantandthenyoutrytowritethecodesothatitexplainshowsomethingisbeingdoneonitsownHoweversometimesyouhavetowritesuchnastycodetosolveaproblemthatitdoesneedacommentoneverylineInthiscaseitrsquosstrictlyforyoutopracticetranslatingcodetoEnglish

CanIusesingle-quotesordouble-quotestomakeastringordo

theydodifferentthingsInPythoneitherwaytomakeastringisacceptablealthoughtypicallyyoursquollusesingle-quotesforanyshortstringslikeaorsnow

Exercise8PrintingPrinting

WewillnowseehowtodoamorecomplicatedformattingofastringThiscodelookscomplexbutifyoudoyourcommentsaboveeachlineandbreakeachthingdowntoitspartsyoursquollunderstanditClickheretoviewcodeimage

ex8py

1formatter=

2

3print(formatterformat(1234))

4print(formatterformat(onetwothreefour))

5print(formatterformat(TrueFalseFalseTrue))

6print(formatterformat(formatterformatterformatter

formatter))

7print(formatterformat(

8Tryyour

9Owntexthere

10Maybeapoem

11Orasongaboutfear

12))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise8Session

$python36ex8py

1234

onetwothreefour

TrueFalseFalseTrue

TryyourOwntexthereMaybeapoemOrasongaboutfearInthis

exerciseIrsquomusingsomethingcalledafunctiontoturntheformatter

variableintootherstringsWhenyouseemewrite

formatterformat()Irsquomtellingpythontodothefollowing1Take

theformatterstringdefinedonline1

2Callitsformatfunctionwhichissimilartotellingittodoacommandlinecommandnamedformat

3PasstoformatfourargumentswhichmatchupwiththefoursintheformattervariableThisislikepassingargumentstothecommandlinecommandformat

4TheresultofcallingformatonformatterisanewstringthathasthereplacedwiththefourvariablesThisiswhatprintisnowprintingout

ThatrsquosalotfortheeighthexercisesowhatIwantyoutodoisconsiderthisabrainteaserItrsquosalrightifyoudonrsquotreallyunderstandwhatrsquosgoingonbecausetherestofthebookwillslowlymakethisclearAtthispointtrytostudythisandseewhatrsquosgoingonthenmoveontothenextexercise

StudyDrillsDoyourcheckswritedownyourmistakesandtrynottomakethesamemistakesonthenextexerciseInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIhavetoputquotesaroundonebutnotaroundTrueorFalsePythonrecognizesTrueandFalseaskeywordsrepresentingtheconceptoftrueandfalseIfyouputquotesaroundthemthentheyareturnedintostringsandwonrsquotworkYoursquolllearnmoreabouthowtheseworkinExercise27

CanIuseIDLEtorunthisNoyoushouldlearntousethecommandlineItisessentialtolearningprogrammingandisagoodplacetostartifyouwanttolearnaboutprogrammingIDLEwillfailforyouwhenyougetfurtherinthebook

Exercise9PrintingPrintingPrinting

BynowyoushouldrealizethepatternforthisbookistousemorethanoneexercisetoteachyousomethingnewIstartwithcodethatyoumightnotunderstandthenmoreexercisesexplaintheconceptIfyoudonrsquotunderstandsomethingnowyouwilllaterasyoucompletemoreexercisesWritedownwhatyoudonrsquotunderstandandkeepgoingClickheretoviewcodeimage

ex9py

1Heressomenewstrangestuffremembertypeitexactly

2

3days=MonTueWedThuFriSatSun

4months=JannFebnMarnAprnMaynJunnJulnAug

5

6print(Herearethedaysdays)

7print(Herearethemonthsmonths)

8

9print(

10Theressomethinggoingonhere

11Withthethreedouble-quotes

12Wellbeabletotypeasmuchaswelike

13Even4linesifwewantor5or6

14)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise9Session

$python36ex9py

HerearethedaysMonTueWedThuFriSatSun

HerearethemonthsJan

Feb

Mar

Apr

May

Jun

Jul

Aug

Theressomethinggoingonhere

Withthethreedouble-quotes

Wellbeabletotypeasmuchaswelike

Even4linesifwewantor5or6

StudyDrillsCheckyourworkwritedownyourmistakestrynottomakethemonthenextexerciseAreyoubreakingyourcodeandthenfixingitInotherwordsrepeattheStudyDrillsfromExercise7

CommonStudentQuestionsWhydoIgetanerrorwhenIputspacesbetweenthethreedouble-quotesYouhavetotypethemlikeandnotmeaningwithnospacesbetweeneachone

WhatifIwantedtostartthemonthsonanewlineYousimplystartthestringwithnlikethisClickheretoviewcodeimagenJannFebnMarnAprnMaynJunnJulnAug

IsitbadthatmyerrorsarealwaysspellingmistakesMostprogrammingerrorsinthebeginning(andevenlater)aresimplespellingmistakestyposorgettingsimplethingsoutoforder

Exercise10WhatWasThat

InExercise9IthrewyousomenewstuffjusttokeepyouonyourtoesIshowedyoutwowaystomakeastringthatgoesacrossmultiplelinesInthefirstwayIputthecharactersn(backslashn)betweenthenamesofthemonthsThesetwocharactersputanewlinecharacterintothestringatthatpointThis(backslash)characterencodesdifficult-to-typecharactersintoastringTherearevariousescapesequencesavailablefordifferentcharactersyoumightwanttouseWersquolltryafewofthesesequencessoyoucanseewhatImeanAnimportantescapesequenceistoescapeasingle-quote()ordouble-quote()Imagineyouhaveastringthatusesdouble-quotesandyouwanttoputadouble-quoteinsidethestringIfyouwriteIunderstandjoethenPythonwillgetconfusedbecauseitwillthinkthedouble-quotesaroundunderstandactuallyendsthestringYouneedawaytotellPythonthatthedouble-quoteinsidethestringisnrsquotarealdouble-quoteTosolvethisproblemyouescapedouble-quotesandsingle-quotessoPythonknowstoincludetheminthestringHerersquosanexampleClickheretoviewcodeimage

Iam62tallescapedoublendashquoteinsidestring

Iam62tallescapesinglendashquoteinsidestringThesecond

wayisbyusingtriple-quoteswhichisjustandworkslikea

stringbutyoualsocanputasmanylinesoftextasyouwantuntil

youtypeagainWersquollalsoplaywiththese

Clickheretoviewcodeimage

ex10py

1tabby_cat=tImtabbedin

2persian_cat=Imsplitnonaline

3backslash_cat=Imacat

4

5fat_cat=

6Illdoalist

7tCatfood

8tFishies

9tCatnipntGrass

10

11

12print(tabby_cat)

13print(persian_cat)

14print(backslash_cat)

15print(fat_cat)

WhatYouShouldSeeLookforthetabcharactersthatyoumadeInthisexercisethespacingisimportanttogetright

$pythonex10py

Imtabbedin

Imsplit

onaline

Imacat

Illdoalist

Catfood

Fishies

Catnip

Grass

EscapeSequencesThisisalloftheescapesequencesPythonsupportsYoumaynotusemanyofthesebutmemorizetheirformatandwhattheydoanywayTrythemoutinsomestringstoseeifyoucanmakethemwork

StudyDrills1Memorizealltheescapesequencesbyputtingthemonflashcards2Use(triple-single-quote)insteadCanyouseewhyyoumightusethatinsteadof

3Combineescapesequencesandformatstringstocreateamorecomplexformat

CommonStudentQuestionsIstillhavenrsquotcompletelyfiguredoutthelastexerciseShouldIcontinueYeskeepgoingInsteadofstoppingtakenoteslistingthingsyoudonrsquotunderstandforeachexercisePeriodicallygothroughyournotesandseeifyoucanfigurethesethingsoutafteryoursquovecompletedmoreexercisesSometimesthoughyoumayneedtogobackafewexercisesanddothemagain

WhatmakesspecialcomparedtotheotheronesItrsquossimplythewayyouwouldwriteoutonebackslash()characterThinkaboutwhyyouwouldneedthis

WhenIwriteornitdoesnrsquotworkThatrsquosbecauseyouareusingaforward-slash()andnotabackslash()Theyaredifferentcharactersthatdoverydifferentthings

IdonrsquotgetStudyDrill3WhatdoyoumeanbyldquocombinerdquoescapesequencesandformatsOneconceptIneedyoutounderstandisthateachoftheseexercisescanbecombinedtosolveproblemsTakewhatyouknowaboutformatstringsandwritesomenewcodethatusesformatstringsandtheescapesequencesfromthisexercise

WhatrsquosbetterorItrsquosentirelybasedonstyleGowiththe(triple-single-quote)stylefornowbutbereadytouseeitherdependingonwhatfeelsbestorwhateveryoneelseisdoing

Exercise11AskingQuestions

NowitistimetopickupthepaceYouaredoingalotofprintingtogetyoufamiliarwithtypingsimplethingsbutthosesimplethingsarefairlyboringWhatwewanttodonowisgetdataintoyourprogramsThisisalittletrickybecauseyouhavetolearntodotwothingsthatmaynotmakesenserightawaybuttrustmeanddoitanywayItwillmakesenseinafewexercisesMostofwhatsoftwaredoesisthefollowing1Takessomekindofinputfromaperson

2Changesit3Printsoutsomethingtoshowhowitchanged

SofaryouhavebeenprintingstringsbutyouhavenrsquotbeenabletogetanyinputfromapersonYoumaynotevenknowwhatldquoinputrdquomeansbuttypethiscodeinanywayandmakeitexactlythesameInthenextexercisewersquolldomoretoexplaininputClickheretoviewcodeimage

ex11py

1print(Howoldareyouend=)

2age=input()

3print(Howtallareyouend=)

4height=input()

5print(Howmuchdoyouweighend=)

6weight=input()

7

8print(fSoyoureageoldheighttallandweight

heavy)

WarningWeputanend=attheendofeachprintlineThistellsprinttonotendthelinewithanewlinecharacterandgotothenextline

WhatYouShouldSeeClickheretoviewcodeimage

Exercise11Session

$python36ex11py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1GoonlineandfindoutwhatPythonrsquosinputdoes2CanyoufindotherwaystouseitTrysomeofthesamplesyoufind3Writeanotherldquoformrdquolikethistoasksomeotherquestions

CommonStudentQuestionsHowdoIgetanumberfromsomeonesoIcandomathThatrsquosalittleadvancedbuttryx=int(input())whichgetsthenumberasastringfrominput()thenconvertsittoanintegerusingint()

Iputmyheightintorawinputlikethisinput(62)butitdoesnrsquotworkDonrsquotputyourheightintheretypeitdirectlyintoyourTerminalFirstgobackandmakethecodeexactlylikemineNextrunthescriptandwhenitpausestypeyourheightinatyourkeyboardThatrsquosallthereistoit

Exercise12PromptingPeople

Whenyoutypedinput()youweretypingthe(and)characterswhichareparenthesischaractersThisissimilartowhenyouusedthemtodoaformatwithextravariablesasinfxyForinputyoucanalsoputinaprompttoshowtoapersonsoheknowswhattotypePutastringthatyouwantforthepromptinsidethe()sothatitlookslikethis

y=input(Name)

ThispromptstheuserwithldquoNamerdquoandputstheresultintothevariableyThisishowyouasksomeoneaquestionandgettheanswerThismeanswecancompletelyrewriteourpreviousexerciseusingjustinputtodoallthepromptingClickheretoviewcodeimage

ex12py

1age=input(Howoldareyou)

2height=input(Howtallareyou)

3weight=input(Howmuchdoyouweigh)

4

5print(fSoyoureageoldheighttallandweight

heavy)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise12Session

$python36ex12py

Howoldareyou38

Howtallareyou62

Howmuchdoyouweigh180lbs

Soyoure38old62talland180lbsheavy

StudyDrills1InTerminalwhereyounormallyrunpython36torunyourscriptstypepydocinputReadwhatitsaysIfyoursquoreonWindowstry

python36-mpydocinputinstead2Getoutofpydocbytypingqtoquit3Lookonlineforwhatthepydoccommanddoes4UsepydoctoalsoreadaboutopenfileosandsysItrsquosalrightifyoudonotunderstandthosejustreadthroughandtakenotesaboutinterestingthings

CommonStudentQuestionsHowcomeIgetSyntaxErrorinvalidsyntaxwheneverIrunpydocYouarenrsquotrunningpydocfromthecommandlineyoursquoreprobablyrunningitfrominsidepython36Exitoutofpython36first

WhydoesmypydocnotpauselikeyoursdoesSometimesifthehelpdocumentisshortenoughtofitononescreenthenpydocwilljustprintit

WhenIrunpydocIgetmoreisnotrecognizedasaninternalSomeversionsofWindowsdonothavethatcommandwhichmeanspydocisbrokenforyouYoucanskipthisStudyDrillandjustsearchonlineforPythondocumentationwhenyouneedit

WhycanrsquotIdoprint(Howoldareyouinput())Youcanbutthentheresultofcallinginput()isneversavedtoavariableanditrsquollworkinastrangewayTrythisandthentrytoprintoutwhatyoutypeSeeifyoucandebugwhythisisnrsquotworking

Exercise13ParametersUnpackingVariables

Inthisexercisewewillcoveronemoreinputmethodyoucanusetopassvariablestoascript(scriptbeinganothernameforyourpyfiles)Youknowhowyoutypepython36ex13pytoruntheex13pyfileWelltheex13pypartofthecommandiscalledanargumentWhatwersquolldonowiswriteascriptthatalsoacceptsargumentsTypethisprogramandIrsquollexplainitindetailClickheretoviewcodeimage

ex13py

1fromsysimportargv

2readtheWYSSsectionforhowtorunthis

3scriptfirstsecondthird=argv

4

5print(Thescriptiscalledscript)

6print(Yourfirstvariableisfirst)

7print(Yoursecondvariableissecond)

8print(Yourthirdvariableisthird)

Online1wehavewhatrsquoscalledanimportThisishowyouaddfeaturestoyourscriptfromthePythonfeaturesetRatherthangiveyouallthefeaturesatoncePythonasksyoutosaywhatyouplantouseThiskeepsyourprogramssmallbutitalsoactsasdocumentationforotherprogrammerswhoreadyourcodelaterTheargvistheargumentvariableaverystandardnameinprogrammingthatyouwillfindusedinmanyotherlanguagesThisvariableholdstheargumentsyoupasstoyourPythonscriptwhenyourunitIntheexercisesyouwillgettoplaywiththismoreandseewhathappensLine3unpacksargvsothatratherthanholdingalltheargumentsitgetsassignedtofourvariablesyoucanworkwithscriptfirstsecondandthirdThismaylookstrangebutldquounpackrdquoisprobablythebestwordtodescribewhatitdoesItjustsaysldquoTakewhateverisinargvunpackitandassignittoallofthesevariablesontheleftinorderrdquoAfterthatwejustprintthemoutlikenormal

HoldUpFeaturesHaveAnotherName

Icallthemldquofeaturesrdquohere(theselittlethingsyouimporttomakeyourPythonprogramdomore)butnobodyelsecallsthemfeaturesIjustusedthatnamebecauseIneededtotrickyouintolearningwhattheyarewithoutjargonBeforeyoucancontinueyouneedtolearntheirrealnamemodulesFromnowonwewillbecallingtheseldquofeaturesrdquothatweimportmodulesIrsquollsaythingslikeldquoYouwanttoimportthesysmodulerdquoTheyarealsocalledldquolibrariesrdquobyotherprogrammersbutletrsquosjuststickwithmodules

WhatYouShouldSee

WarningPayattentionYouhavebeenrunningpythonscriptswithoutcommandlineargumentsIfyoutypeonlypython36ex13pyyouaredoingitwrongPaycloseattentiontohowIrunitThisappliesanytimeyouseeargvbeingused

Runtheprogramlikethis(andyoumustpassthreecommandlinearguments)Clickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd3rd

Thescriptiscalledex13py

Yourfirstvariableisfirst

Yoursecondvariableis2nd

Yourthirdvariableis3rd

ThisiswhatyoushouldseewhenyoudoafewdifferentrunswithdifferentargumentsClickheretoviewcodeimage

Exercise13Session

$python36ex13pystuffthingsthat

Thescriptiscalledex13py

Yourfirstvariableisstuff

Yoursecondvariableisthings

Yourthirdvariableisthat

$

$python36ex13pyappleorangegrapefruit

Thescriptiscalledex13py

Yourfirstvariableisapple

Yoursecondvariableisorange

Yourthirdvariableisgrapefruit

Youcanactuallyreplacefirst2ndand3rdwithanythreethingsyouwantIfyoudonotrunitcorrectlythenyouwillgetanerrorlikethisClickheretoviewcodeimage

Exercise13Session

$python36ex13pyfirst2nd

Traceback(mostrecentcalllast)

Fileex13pyline3inltmodulegt

scriptfirstsecondthird=argv

ValueErrornotenoughvaluestounpack(expected4got3)

Thishappenswhenyoudonotputenoughargumentsonthecommandwhenyourunit(inthiscasejustfirst2nd)NoticethatwhenIrunitIgiveitfirst2ndwhichcausedittogiveanerroraboutldquoneedmorethan3valuestounpackrdquotellingyouthatyoudidnrsquotgiveitenoughparameters

StudyDrills1TrygivingfewerthanthreeargumentstoyourscriptSeethaterroryougetSeeifyoucanexplainit

2WriteascriptthathasfewerargumentsandonethathasmoreMakesureyougivetheunpackedvariablesgoodnames

3CombineinputwithargvtomakeascriptthatgetsmoreinputfromauserDonrsquotoverthinkitJustuseargvtogetsomethingandinputtogetsomethingelsefromtheuser

4RememberthatmodulesgiveyoufeaturesModulesModulesRememberthisbecausewersquollneeditlater

CommonStudentQuestionsWhenIrunitIgetValueErrorneedmorethan1valuetounpackRememberthatanimportantskillispayingattentiontodetailsIfyoulookattheWhatYouShouldSeesectionyouseethatIrunthescriptwithparametersonthecommandlineYoushouldreplicatehowIranitexactly

Whatrsquosthedifferencebetweenargvandinput()ThedifferencehastodowithwheretheuserisrequiredtogiveinputIftheygiveyourscriptinputsonthecommandlinethenyouuseargvIfyouwantthemtoinputusingthekeyboardwhilethescriptisrunningthenuseinput()

ArethecommandlineargumentsstringsYestheycomeinasstringsevenifyoutypednumbersonthecommandlineUseint()toconvertthemlikewithint(input())

HowdoyouusethecommandlineYoushouldhavelearnedtouseitveryquicklyandfluentlybynowbutifyouneedtolearnitatthisstagethenreadtheappendix

Icanrsquotcombineargvwithinput()DonrsquotoverthinkitJustslaptwolinesattheendofthisscriptthatuseinput()togetsomethingandthenprintitFromthatstartplayingwithmorewaystousebothinthesamescript

WhycanrsquotIdothisinput()=xBecausethatrsquosbackwardtohowitshouldworkDoitthewayIdoitanditrsquollwork

Exercise14PromptingandPassing

LetrsquosdooneexercisethatusesargvandinputtogethertoasktheusersomethingspecificYouwillneedthisforthenextexercisewhereyoulearntoreadandwritefilesInthisexercisewersquolluseinputslightlydifferentlybyhavingitprintasimplegtpromptThisissimilartogameslikeZorkorAdventureClickheretoviewcodeimage

ex14py

1fromsysimportargv

2

3scriptuser_name=argv

4prompt=gt

5

6print(fHiuser_nameImthescriptscript)

7print(Idliketoaskyouafewquestions)

8print(fDoyoulikemeuser_name)

9likes=input(prompt)

10

11print(fWheredoyouliveuser_name)

12lives=input(prompt)

13

14print(Whatkindofcomputerdoyouhave)

15computer=input(prompt)

16

17print(f

18Alrightsoyousaidlikesaboutlikingme

19YouliveinlivesNotsurewherethatis

20AndyouhaveacomputercomputerNice

21)Wemakeavariablepromptthatissettothepromptwe

wantandwegivethattoinputinsteadoftypingitoverandover

Nowifwewanttomakethepromptsomethingelsewejustchangeit

inthisonespotandrerunthescriptVeryhandy

WhatYouShouldSeeWhenyourunthisrememberthatyouhavetogivethescriptyournamefortheargvargumentsClickheretoviewcodeimage

Exercise14Session

$python36ex14pyzed

HizedImtheex14pyscript

Idliketoaskyouafewquestions

Doyoulikemezed

gtYes

Wheredoyoulivezed

gtSanFrancisco

Whatkindofcomputerdoyouhave

gtTandy1000

AlrightsoyousaidYesaboutlikingme

YouliveinSanFranciscoNotsurewherethatis

AndyouhaveaTandy1000computerNice

StudyDrills1FindoutwhatthegamesZorkandAdventurewereTrytofindcopiesandplaythem

2Changethepromptvariabletosomethingelseentirely3Addanotherargumentanduseitinyourscriptthesamewayyoudidinthepreviousexercisewithfirstsecond=ARGV

4MakesureyouunderstandhowIcombinedastylemultilinestringwiththeformatactivatorasthelastprint

CommonStudentQuestionsIgetSyntaxErrorinvalidsyntaxwhenIrunthisscriptAgainyouhavetorunitrightonthecommandlinenotinsidePythonIfyoutypepython36andthentrytotypepython36ex14pyZeditwillfailbecauseyouarerunningPythoninsidePythonCloseyourwindowandthenjusttypepython36ex14pyZed

IdonrsquotunderstandwhatyoumeanbychangingthepromptSeethevariableprompt=gtChangethattohaveadifferentvalueYouknowthisitrsquosjustastringandyoursquovedone13exercisesmakingthemsotakethetimetofigureitout

IgettheerrorValueErrorneedmorethan1valuetounpackRememberwhenIsaidyouneedtolookattheWhatYouShouldSeesectionandreplicatewhatIdidYouneedtodothesamethinghereandfocusonhowItypethecommandinandwhyIhaveacommandlineargument

HowcanIrunthisfromIDLEDonrsquotuseIDLECanIusedouble-quotesforthepromptvariableYoutotallycanGoaheadandtrythat

YouhaveaTandycomputerIdidwhenIwaslittleIgetNameErrornamepromptisnotdefinedwhenIrunitYoueitherspelledthenameofthepromptvariablewrongorforgotthatlineGobackandcompareeachlineofcodetominestartingatthebottomofthescriptandworkinguptothetopAnytimeyouseethiserroritmeansyouspelledsomethingwrongorforgottocreatethevariable

Exercise15ReadingFiles

YouknowhowtogetinputfromauserwithinputorargvNowyouwilllearnaboutreadingfromafileYoumayhavetoplaywiththisexercisethemosttounderstandwhatrsquosgoingonsodotheexercisecarefullyandrememberyourchecksWorkingwithfilesisaneasywaytoeraseyourworkifyouarenotcarefulThisexerciseinvolveswritingtwofilesOneistheusualex15pyfilethatyouwillrunbuttheotherisnamedex15_sampletxtThissecondfileisnrsquotascriptbutaplaintextfilewersquollbereadinginourscriptHerearethecontentsofthatfileClickheretoviewcodeimage

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

WhatwewanttodoisopenthatfileinourscriptandprintitoutHoweverwedonotwanttojusthardcodethenameex15_sampletxtintoourscriptldquoHardcodingrdquomeansputtingsomebitofinformationthatshouldcomefromtheuserasastringdirectlyinoursourcecodeThatrsquosbadbecausewewantittoloadotherfileslaterThesolutionistouseargvorinputtoasktheuserwhatfiletoopeninsteadofhardcodingthefilersquosnameClickheretoviewcodeimage

ex15py

1fromsysimportargv

2

3scriptfilename=argv

4

5txt=open(filename)

6

7print(fHeresyourfilefilename)

8print(txtread())

9

10print(Typethefilenameagain)

11file_again=input(gt)

12

13txt_again=open(file_again)

14

15print(txt_againread())Afewfancythingsaregoingoninthis

filesoletrsquosbreakitdownrealquicklybullLines1ndash3useargvto

getafilenameNextwehaveline5whereweuseanewcommand

openRightnowrunpydocopenandreadtheinstructionsNotice

howlikeyourownscriptsandinputittakesaparameterand

returnsavalueyoucansettoyourownvariableYoujustopeneda

file

bullLine7printsalittlemessagebutonline8wehavesomethingverynewandexcitingWecallafunctionontxtnamedreadWhatyougetbackfromopenisafileanditalsohascommandsyoucangiveitYougiveafileacommandbyusingthe(dotorperiod)thenameofthecommandandparametersjustlikewithopenandinputThedifferenceisthattxtread()saysldquoHeytxtDoyourreadcommandwithnoparametersrdquo

TheremainderofthefileismoreofthesamebutwersquollleavetheanalysistoyouintheStudyDrills

WhatYouShouldSee

WarningPayattentionIsaidpayattentionYouhavebeenrunningscriptswithjustthenameofthescriptbutnowthatyouareusingargvyouhavetoaddargumentsLookattheveryfirstlineoftheexamplebelowandyouwillseeIdopythonex15pyex15_sampletxttorunitSeetheextraargumentex15_sampletxtaftertheex15pyscriptnameIfyoudonottypethatyouwillgetanerrorsopayattention

Imadeafilecalledex15_sampletxtandranmyscriptClickheretoviewcodeimage

Exercise15Session

$python36ex15pyex15_sampletxt

Heresyourfileex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

Typethefilenameagain

gtex15_sampletxt

ThisisstuffItypedintoafile

Itisreallycoolstuff

Lotsandlotsoffuntohaveinhere

StudyDrillsThisisabigjumpsobesureyoudothisStudyDrillasbestyoucanbeforemovingon

1AboveeachlinecommentoutinEnglishwhatthatlinedoes2IfyouarenotsureasksomeoneforhelporsearchonlineManytimessearchingforldquopython36THINGrdquowillfindanswerstowhatthatTHINGdoesinPythonTrysearchingforldquopython36openrdquo

3IusedthewordldquocommandsrdquoherebutcommandsarealsocalledldquofunctionsrdquoandldquomethodsrdquoYouwilllearnaboutfunctionsandmethodslaterinthebook

4Getridoflines10ndash15whereyouuseinputandrunthescriptagain5UseonlyinputandtrythescriptthatwayWhyisonewayofgettingthefilenamebetterthananother

6Startpython36tostartthepython36shellanduseopenfromthepromptjustlikeinthisprogramNoticehowyoucanopenfilesandrunreadonthemfromwithinpython36

7Haveyourscriptalsocallclose()onthetxtandtxt_againvariablesItrsquosimportanttoclosefileswhenyouaredonewiththem

CommonStudentQuestionsDoestxt=open(filename)returnthecontentsofthefileNoitdoesnrsquotItactuallymakessomethingcalledafileobjectYoucanthinkofafilelikeanoldtapedrivethatyousawonmainframecomputersinthe1950sorevenlikeaDVDplayerfromtodayYoucanmovearoundinsidethemandthenldquoreadrdquothembuttheDVDplayerisnottheDVDthesamewaythefileobjectisnotthefilersquoscontents

IcanrsquottypecodeintoTerminalPowerShelllikeyousayinStudyDrill7Firstfromthecommandlinejusttypepython36andpressEnterNowyouareinpython36aswersquovedoneafewothertimesThenyoucantypeincodeandPythonwillrunitinlittlepiecesPlaywiththatTogetoutofittypequit()andhitEnter

WhyistherenoerrorwhenweopenthefiletwicePythonwillnotrestrictyoufromopeningafilemorethanonceandsometimesthisisnecessary

WhatdoesfromsysimportargvmeanFornowjustunderstandthatsysisapackageandthisphrasejustsaystogettheargvfeaturefromthatpackageYoursquolllearnmoreabouttheselater

Iputthenameofthefileinasscriptex15_sampletxt=argvbutitdoesnrsquotworkNothatrsquosnothowyoudoitMakethecodeexactlylikeminethenrunitfromthecommandlinetheexactsamewayIdoYoudonrsquotputthenamesoffilesinyouletPythonputthenamein

Exercise16ReadingandWritingFiles

IfyoudidtheStudyDrillsfromthelastexerciseyoushouldhaveseenallsortsofcommands(methodsfunctions)youcangivetofilesHerersquosthelistofcommandsIwantyoutorememberbullcloseClosesthefileLikeFile-gtSaveinyoureditor

bullreadReadsthecontentsofthefileYoucanassigntheresulttoavariable

bullreadlineReadsjustonelineofatextfilebulltruncateEmptiesthefileWatchoutifyoucareaboutthefilebullwrite(stuff)Writesldquostuffrdquotothefilebullseek(0)Movesthereadwritelocationtothebeginningofthefile

OnewaytorememberwhateachofthesedoesistothinkofavinylrecordcassettetapeVHStapeDVDorCDplayerIntheearlydaysofcomputersdatawasstoredoneachofthesekindsofmediasomanyofthefileoperationsstillresembleastoragesystemthatislinearTapeandDVDdrivesneedtoldquoseekrdquoaspecificspotandthenyoucanreadorwriteatthatspotTodaywehaveoperatingsystemsandstoragemediathatblurthelinesbetweenrandomaccessmemoryanddiskdrivesbutwestillusetheolderideaofalineartapewithareadwriteheadthatmustbemovedFornowthesearetheimportantcommandsyouneedtoknowSomeofthemtakeparametersbutwedonotreallycareaboutthatYouonlyneedtorememberthatwritetakesaparameterofastringyouwanttowritetothefileLetrsquosusesomeofthistomakeasimplelittletexteditorClickheretoviewcodeimage

ex16py

1fromsysimportargv

2

3scriptfilename=argv

4

5print(fWeregoingtoerasefilename)

6print(IfyoudontwantthathitCTRL-C(^C))

7print(IfyoudowantthathitRETURN)

8

9input()

10

11print(Openingthefile)

12target=open(filenamew)

13

14print(TruncatingthefileGoodbye)

15targettruncate()

16

17print(NowImgoingtoaskyouforthreelines)

18

19line1=input(line1)

20line2=input(line2)

21line3=input(line3)

22

23print(Imgoingtowritethesetothefile)

24

25targetwrite(line1)

26targetwrite(n)

27targetwrite(line2)

28targetwrite(n)

29targetwrite(line3)

30targetwrite(n)

31

32print(Andfinallywecloseit)

33targetclose()

ThatrsquosalargefileprobablythelargestyouhavetypedinSogoslowdoyourchecksandmakeitrunOnetrickistogetbitsofitrunningatatimeGetlines1ndash8runningthenfivemorethenafewmoreuntilitrsquosalldoneandrunning

WhatYouShouldSeeThereareactuallytwothingsyouwillseeFirsttheoutputofyournewscriptClickheretoviewcodeimage

Exercise16Session

$python36ex16pytesttxt

Weregoingtoerasetesttxt

IfyoudontwantthathitCTRL-C(^C)

IfyoudowantthathitRETURN

Openingthefile

TruncatingthefileGoodbye

NowImgoingtoaskyouforthreelines

line1Maryhadalittlelamb

line2Itsfleecewaswhiteassnow

line3Itwasalsotasty

Imgoingtowritethesetothefile

Andfinallywecloseit

Nowopenupthefileyoumade(inmycasetesttxt)inyoureditorandcheckitoutNeatright

StudyDrills1IfyoudonotunderstandthisgobackthroughandusethecommenttricktogetitsquaredawayinyourmindOnesimpleEnglishcommentaboveeachlinewillhelpyouunderstandoratleastletyouknowwhatyouneedtoresearchmore

2Writeascriptsimilartothelastexercisethatusesreadandargvtoreadthefileyoujustcreated

3TherersquostoomuchrepetitioninthisfileUsestringsformatsandescapestoprintoutline1line2andline3withjustonetargetwrite()commandinsteadofsix

4FindoutwhywehadtopassawasanextraparametertoopenHintopentriestobesafebymakingyouexplicitlysayyouwanttowriteafile

5Ifyouopenthefilewithwmodethendoyoureallyneedthetargettruncate()ReadthedocumentationforPythonrsquosopenfunctionandseeifthatrsquostrue

CommonStudentQuestionsIsthetruncate()necessarywiththewparameterSeeStudyDrillsnumber5

WhatdoeswmeanItrsquosreallyjustastringwithacharacterinitforthekindofmodeforthefileIfyouusewthenyoursquoresayingldquoopenthisfileinlsquowritersquomoderdquothusthewcharacterTherersquosalsorforldquoreadrdquoaforldquoappendrdquoandmodifiersonthese

WhatmodifierstothefilemodescanIuseThemostimportantonetoknowfornowisthe+modifiersoyoucandow+r+anda+Thiswillopenthefileinbothreadandwritemodeanddependingonthecharacterusepositionthefileindifferentways

Doesjustdoingopen(filename)openitinr(read)modeYesthatrsquosthedefaultfortheopen()function

Exercise17MoreFiles

NowletrsquosdoafewmorethingswithfilesWersquollwriteaPythonscripttocopyonefiletoanotherItrsquollbeveryshortbutwillgiveyouideasaboutotherthingsyoucandowithfilesClickheretoviewcodeimage

ex17py

1fromsysimportargv

2fromospathimportexists

3

4scriptfrom_fileto_file=argv

5

6print(fCopyingfromfrom_filetoto_file)

7

8wecoulddothesetwoononelinehow

9in_file=open(from_file)

10indata=in_fileread()

11

12print(fTheinputfileislen(indata)byteslong)

13

14print(fDoestheoutputfileexistexists(to_file))

15print(ReadyhitRETURNtocontinueCTRL-Ctoabort)

16input()

17

18out_file=open(to_filew)

19out_filewrite(indata)

20

21print(Alrightalldone)

22

23out_fileclose()

24in_fileclose()Youshouldimmediatelynoticethatweimport

anotherhandycommandnamedexistsThisreturnsTrueifafile

existsbasedonitsnameinastringasanargumentItreturns

FalseifnotWersquollbeusingthisfunctioninthesecondhalfofthis

booktodolotsofthingsbutrightnowyoushouldseehowyoucan

importit

Usingimportisawaytogettonsoffreecodeotherbetter(wellusually)programmershavewrittensoyoudonothavetowriteit

WhatYouShouldSee

JustlikeyourotherscriptsrunthisonewithtwoargumentsthefiletocopyfromandthefiletocopyittoIrsquomgoingtouseasimpletestfilenamedtesttxtClickheretoviewcodeimage

Exercise17Session

$firstmakeasamplefile

$echoThisisatestfilegttesttxt

$thenlookatit

$cattesttxt

Thisisatestfile

$nowrunourscriptonit

$python36ex17pytesttxtnew_filetxt

Copyingfromtesttxttonew_filetxt

Theinputfileis21byteslong

DoestheoutputfileexistFalse

ReadyhitRETURNtocontinueCTRL-Ctoabort

Alrightalldone

ItshouldworkwithanyfileTryabunchmoreandseewhathappensJustbecarefulyoudonotblastanimportantfile

WarningDidyouseethetrickIdidwithechotomakeafileandcattoshowthefileYoucanlearnhowtodothatintheAppendixldquoCommandLineCrashCourserdquo

StudyDrills1ThisscriptisreallyannoyingTherersquosnoneedtoaskyoubeforedoingthecopyanditprintstoomuchouttothescreenTrytomakethescriptmorefriendlytousebyremovingfeatures

2SeehowshortyoucanmakethescriptIcouldmakethisonelinelong3NoticeattheendoftheWhatYouShouldSeesectionIusedsomethingcalledcatItrsquosanoldcommandthatconcatenatesfilestogetherbutmostlyitrsquosjustaneasywaytoprintafiletothescreenTypemancattoreadaboutit

4Findoutwhyyouhadtowriteout_fileclose()inthecode

5GoreaduponPythonrsquosimportstatementandstartpython36totryitoutTryimportingsomethingsandseeifyoucangetitrightItrsquosalrightifyoudonot

CommonStudentQuestionsWhyisthewinquotesThatrsquosastringYoursquovebeenusingstringsforawhilenowMakesureyouknowwhatastringis

NowayyoucanmakethisonelineThatdependsonhowyoudefineonelineofcode

IsitnormaltofeellikethisexercisewasreallyhardYesitistotallynormalProgrammingmaynotldquoclickrdquoforyouuntilmaybeevenExercise36oritmightnotuntilyoufinishthebookandthenmakesomethingwithPythonEveryoneisdifferentsojustkeepgoingandkeepreviewingexercisesthatyouhadtroublewithuntilitclicksBepatient

Whatdoesthelen()functiondoItgetsthelengthofthestringthatyoupasstoitthenreturnsthatasanumberPlaywithit

WhenItrytomakethisscriptshorterIgetanerrorwhenIclosethefilesattheendYouprobablydidsomethinglikeindata=open(from_file)read()whichmeansyoudonrsquotneedtothendoin_fileclose()whenyoureachtheendofthescriptItshouldalreadybeclosedbyPythononcethatonelineruns

IgetaSyntaxEOLwhilescanningstringliteralerrorYouforgottoendastringproperlywithaquoteGolookatthatlineagain

Exercise18NamesVariablesCodeFunctions

BigtitlerightIamabouttointroduceyoutothefunctionDumdumdahEveryprogrammerwillgoonandonaboutfunctionsandallthedifferentideasabouthowtheyworkandwhattheydobutIwillgiveyouthesimplestexplanationyoucanuserightnowFunctionsdothreethings1Theynamepiecesofcodethewayvariablesnamestringsandnumbers

2Theytakeargumentsthewayyourscriptstakeargv3Using1and2theyletyoumakeyourownldquomini-scriptsrdquoorldquotinycommandsrdquo

YoucancreateafunctionbyusingtheworddefinPythonIrsquomgoingtohaveyoumakefourdifferentfunctionsthatworklikeyourscriptsandthenIrsquollshowyouhoweachoneisrelatedClickheretoviewcodeimage

ex18py

1thisoneislikeyourscriptswithargv

2defprint_two(args)

3arg1arg2=args

4print(farg1arg1arg2arg2)

5

6okthatargsisactuallypointlesswecanjustdothis

7defprint_two_again(arg1arg2)

8print(farg1arg1arg2arg2)

9

10thisjusttakesoneargument

11defprint_one(arg1)

12print(farg1arg1)

13

14thisonetakesnoarguments

15defprint_none()

16print(Igotnothin)

17

18

19print_two(ZedShaw)

20print_two_again(ZedShaw)

21print_one(First)

22print_none()Letrsquosbreakdownthefirstfunctionprint_two

whichisthemostsimilartowhatyoualreadyknowfrommaking

scripts1WetellPythonwewanttomakeafunctionusingdeffor

ldquodefinerdquo

2OnthesamelineasdefwegivethefunctionanameInthiscasewejustcalleditldquoprint_twordquobutitcouldalsobeldquopeanutsrdquoItdoesnrsquotmatterexceptthatyourfunctionshouldhaveashortnamethatsayswhatitdoes

3Wetellitwewantargs(asteriskargs)whichisalotlikeyourargvparameterbutforfunctionsThishastogoinsideparenthesestowork

4Weendthislinewitha(colon)andstartindenting5Afterthecolonallthelinesthatareindentedfourspaceswillbecomeattachedtoprint_twoOurfirstindentedlineisonethatunpackstheargumentsthesameaswithyourscripts

6Todemonstratehowitworksweprinttheseargumentsoutjustlikewewouldinascript

Theproblemwithprint_twoisthatitrsquosnottheeasiestwaytomakeafunctionInPythonwecanskipthewholeunpackingargumentsandjustusethenameswewantrightinsideparenthesesThatrsquoswhatprint_two_againdoesAfterthatyouhaveanexampleofhowyoumakeafunctionthattakesoneargumentinprint_oneFinallyyouhaveafunctionthathasnoargumentsinprint_none

WarningThisisveryimportantDonotgetdiscouragedrightnowifthisdoesnrsquotquitemakesenseWersquoregoingtodoafewexerciseslinkingfunctionstoyourscriptsandshowyouhowtomakemoreFornowjustkeepthinkingldquomini-scriptrdquowhenIsayldquofunctionrdquoandkeepplayingwiththem

WhatYouShouldSeeIfyourunex18pyyoushouldsee

Exercise18Session

$python36ex18py

arg1Zedarg2Shaw

arg1Zedarg2Shaw

arg1First

Igotnothin

RightawayyoucanseehowafunctionworksNoticethatyouusedyourfunctionsthewayyouusethingslikeexistsopenandothercommandsInfactIrsquovebeentrickingyoubecauseinPythonthosecommandsarejustfunctionsThismeansyoucanmakeyourowncommandsandusetheminyourscriptstoo

StudyDrillsCreateafunctionchecklistforlaterexercisesWritethesechecksonanindexcardandkeepitbyyouwhileyoucompletetherestoftheseexercisesoruntilyoufeelyoudonotneedtheindexcardanymore

1Didyoustartyourfunctiondefinitionwithdef2Doesyourfunctionnamehaveonlycharactersand_(underscore)characters

3Didyouputanopenparenthesisrightafterthefunctionname4Didyouputyourargumentsaftertheparenthesisseparatedbycommas5Didyoumakeeachargumentunique(meaningnoduplicatednames)6Didyouputacloseparenthesisandacolonafterthearguments7DidyouindentalllinesofcodeyouwantinthefunctionfourspacesNomorenoless

8Didyouldquoendrdquoyourfunctionbygoingbacktowritingwithnoindent(dedentingwecallit)

Whenyourun(ldquouserdquoorldquocallrdquo)afunctioncheckthesethings1Didyoucalluserunthisfunctionbytypingitsname

2Didyouputthe(characterafterthenametorunit3Didyouputthevaluesyouwantintotheparenthesesseparatedbycommas

4Didyouendthefunctioncallwitha)characterUsethesetwochecklistsontheremaininglessonsuntilyoudonotneedthemanymoreFinallyrepeatthisafewtimestoyourselfToldquorunrdquoldquocallrdquoorldquouserdquoafunctioneachmeansthesamething

CommonStudentQuestions

CommonStudentQuestionsWhatrsquosallowedforafunctionnameThesameasvariablenamesAnythingthatdoesnrsquotstartwithanumberandislettersnumbersandunderscoreswillwork

WhatdoestheinargsdoThattellsPythontotakealltheargumentstothefunctionandthenputtheminargsasalistItrsquoslikeargvthatyoursquovebeenusingbutforfunctionsItrsquosnotnormallyusedtoooftenunlessspecificallyneeded

ThisfeelsreallyboringandmonotonousThatrsquosgoodItmeansyoursquorestartingtogetbetterattypinginthecodeandunderstandingwhatitdoesTomakeitlessboringtakeeverythingItellyoutotypeinandthenbreakitonpurpose

Exercise19FunctionsandVariables

Functionsmayhavebeenamind-blowingamountofinformationbutdonotworryJustkeepdoingtheseexercisesandgoingthroughyourchecklistfromthelastexerciseandyouwilleventuallygetitThereisonetinypointthatyoumightnothaverealizedwhichwersquollreinforcerightnowThevariablesinyourfunctionarenotconnectedtothevariablesinyourscriptHerersquosanexercisetogetyouthinkingaboutthisClickheretoviewcodeimage

ex19py

1defcheese_and_crackers(cheese_countboxes_of_crackers)

2print(fYouhavecheese_countcheeses)

3print(fYouhaveboxes_of_crackersboxesofcrackers)

4print(Manthatsenoughforaparty)

5print(Getablanketn)

6

7

8print(Wecanjustgivethefunctionnumbersdirectly)

9cheese_and_crackers(2030)

10

11

12print(ORwecanusevariablesfromourscript)

13amount_of_cheese=10

14amount_of_crackers=50

15

16cheese_and_crackers(amount_of_cheeseamount_of_crackers)

17

18

19print(Wecanevendomathinsidetoo)

20cheese_and_crackers(10+205+6)

21

22

23print(Andwecancombinethetwovariablesandmath)

24cheese_and_crackers(amount_of_cheese+100amount_of_crackers

+1000)Thisshowsallthedifferentwayswersquoreabletogiveour

functioncheese_and_crackersthevaluesitneedstoprintthemWe

cangiveitstraightnumbersWecangiveitvariablesWecangive

itmathWecanevencombinemathandvariables

Inawaytheargumentstoafunctionarekindoflikeour=characterwhenwemakeavariableInfactifyoucanuse=tonamesomethingyoucanusually

passittoafunctionasanargument

WhatYouShouldSeeYoushouldstudytheoutputofthisscriptandcompareitwithwhatyouthinkyoushouldgetforeachoftheexamplesinthescriptClickheretoviewcodeimage

Exercise19Session

$python36ex19py

Wecanjustgivethefunctionnumbersdirectly

Youhave20cheeses

Youhave30boxesofcrackers

Manthatsenoughforaparty

Getablanket

ORwecanusevariablesfromourscript

Youhave10cheeses

Youhave50boxesofcrackers

Manthatsenoughforaparty

Getablanket

Wecanevendomathinsidetoo

Youhave30cheeses

Youhave11boxesofcrackers

Manthatsenoughforaparty

Getablanket

Andwecancombinethetwovariablesandmath

Youhave110cheeses

Youhave1050boxesofcrackers

Manthatsenoughforaparty

Getablanket

StudyDrills1GobackthroughthescriptandtypeacommentaboveeachlineexplaininginEnglishwhatitdoes

2Startatthebottomandreadeachlinebackwardsayingalltheimportantcharacters

3Writeatleastonemorefunctionofyourowndesignandrunit10differentways

CommonStudentQuestions

Howcantherepossiblybe10differentwaystorunafunctionBelieveitornottherersquosatheoreticallyinfinitenumberofwaystocallanyfunctionSeehowcreativeyoucangetwithfunctionsvariablesandinputfromauser

IsthereawaytoanalyzewhatthisfunctionisdoingsoIcanunderstanditbetterTherearemanydifferentwaysbuttryputtinganEnglishcommentaboveeachlinedescribingwhatthelinedoesAnothertrickistoreadthecodeoutloudYetanotheristoprintthecodeoutanddrawonthepaperwithpicturesandcommentsshowingwhatrsquosgoingon

WhatifIwanttoasktheuserforthenumbersofcheeseandcrackersYouneedtouseint()toconvertwhatyougetfrominput()

Doesmakingthevariableamount_of_cheesechangethevariablecheese_countinthefunctionNothosevariablesareseparateandliveoutsidethefunctionTheyarethenpassedtothefunctionandtemporaryversionsaremadejustforthefunctionrsquosrunWhenthefunctionexitsthesetemporaryvariablesgoawayandeverythingkeepsworkingKeepgoinginthebookandthisshouldbecomeclearer

Isitbadtohaveglobalvariables(likeamount_of_cheese)withthesamenameasfunctionvariablesYessincethenyoursquorenotquitesurewhichoneyoursquoretalkingaboutButsometimesnecessitymeansyouhavetousethesamenameoryoumightdoitonaccidentJustavoiditwheneveryoucan

IstherealimittothenumberofargumentsafunctioncanhaveItdependsontheversionofPythonandthecomputeryoursquoreonbutitisfairlylargeThepracticallimitthoughisaboutfiveargumentsbeforethefunctionbecomesannoyingtouse

CanyoucallafunctionwithinafunctionYesyoursquollmakeagamethatdoesthislaterinthebook

Exercise20FunctionsandFiles

RememberyourchecklistforfunctionsthendothisexercisepayingcloseattentiontohowfunctionsandfilescanworktogethertomakeusefulstuffClickheretoviewcodeimage

ex20py

1fromsysimportargv

2

3scriptinput_file=argv

4

5defprint_all(f)

6print(fread())

7

8defrewind(f)

9fseek(0)

10

11defprint_a_line(line_countf)

12print(line_countfreadline())

13

14current_file=open(input_file)

15

16print(Firstletsprintthewholefilen)

17

18print_all(current_file)

19

20print(Nowletsrewindkindoflikeatape)

21

22rewind(current_file)

23

24print(Letsprintthreelines)

25

26current_line=1

27print_a_line(current_linecurrent_file)

28

29current_line=current_line+1

30print_a_line(current_linecurrent_file)

31

32current_line=current_line+1

33print_a_line(current_linecurrent_file)Paycloseattentionto

howwepassinthecurrentlinenumbereachtimewerunprint_a_line

WhatYouShouldSee

Clickheretoviewcodeimage

Exercise20Session

$python36ex20pytesttxt

Firstletsprintthewholefile

Thisisline1

Thisisline2

Thisisline3

Nowletsrewindkindoflikeatape

Letsprintthreelines

1Thisisline1

2Thisisline2

3Thisisline3

StudyDrills1WriteanEnglishcommentforeachlinetounderstandwhatthatlinedoes2Eachtimeprint_a_lineisrunyouarepassinginavariablecurrent_lineWriteoutwhatcurrent_lineisequaltooneachfunctioncallandtracehowitbecomesline_countinprint_a_line

3Findeachplaceafunctionisusedandcheckitsdeftomakesurethatyouaregivingittherightarguments

4ResearchonlinewhattheseekfunctionforfiledoesTrypydocfileandseeifyoucanfigureitoutfromthereThentrypydocfileseektoseewhatseekdoes

5Researchtheshorthandnotation+=andrewritethescripttouse+=instead

CommonStudentQuestionsWhatisfintheprint_allandotherfunctionsThefisavariablejustlikeyouhadinotherfunctionsinExercise18exceptthistimeitrsquosafileAfileinPythoniskindoflikeanoldtapedriveonamainframeormaybeaDVDplayerIthasaldquoreadheadrdquoandyoucanldquoseekrdquothisreadheadaroundthefiletopositionsthenworkwithitthereEachtimeyoudofseek(0)yoursquoremovingtothe

startofthefileEachtimeyoudofreadline()yoursquorereadingalinefromthefileandmovingthereadheadtorightafterthenthatendsthatlineThiswillbeexplainedmoreasyougoon

Whydoesseek(0)notsetthecurrent_lineto0Firsttheseek()functionisdealinginbytesnotlinesThecodeseek(0)movesthefiletothe0byte(firstbyte)inthefileSecondcurrent_lineisjustavariableandhasnorealconnectiontothefileatallWearemanuallyincrementingit

Whatis+=YouknowhowinEnglishIcanrewriteldquoitisrdquoasldquoitrsquosrdquoOrIcanrewriteldquoyouarerdquoasldquoyoursquorerdquoInEnglishthisiscalledacontractionandthisiskindoflikeacontractionforthetwooperations=and+Thatmeansx=x+yisthesameasx+=y

Howdoesreadline()knowwhereeachlineisInsidereadline()iscodethatscanseachbyteofthefileuntilitfindsancharacterthenstopsreadingthefiletoreturnwhatitfoundsofarThefilefisresponsibleformaintainingthecurrentpositioninthefileaftereachreadline()callsothatitwillkeepreadingeachline

WhyarethereemptylinesbetweenthelinesinthefileThereadline()functionreturnsthenthatrsquosinthefileattheendofthatlineAddaend=attheendofyourprintfunctioncallstoavoidaddingdoublentoeveryline

Exercise21FunctionsCanReturnSomething

Youhavebeenusingthe=charactertonamevariablesandsetthemtonumbersorstringsWersquorenowgoingtoblowyourmindagainbyshowingyouhowtouse=andanewPythonwordreturntosetvariablestobeavaluefromafunctionTherewillbeonethingtopaycloseattentiontobutfirsttypethisinClickheretoviewcodeimage

ex21py

1defadd(ab)

2print(fADDINGa+b)

3returna+b

4

5defsubtract(ab)

6print(fSUBTRACTINGa-b)

7returna-b

8

9defmultiply(ab)

10print(fMULTIPLYINGab)

11returnab

12

13defdivide(ab)

14print(fDIVIDINGab)

15returnab

16

17

18print(Letsdosomemathwithjustfunctions)

19

20age=add(305)

21height=subtract(784)

22weight=multiply(902)

23iq=divide(1002)

24

25print(fAgeageHeightheightWeightweightIQ

iq)

26

27

28Apuzzlefortheextracredittypeitinanyway

29print(Hereisapuzzle)

30

31what=add(agesubtract(heightmultiply(weightdivide(iq

2))))

32

33print(ThatbecomeswhatCanyoudoitbyhand)Weare

nowdoingourownmathfunctionsforaddsubtractmultiplyand

divideTheimportantthingtonoticeisthelastlinewherewesay

returna+b(inadd)Whatthisdoesisthefollowing1Our

functioniscalledwithtwoargumentsaandb

2WeprintoutwhatourfunctionisdoinginthiscaseldquoADDINGrdquo3WetellPythontodosomethingkindofbackwardwereturntheadditionofa+bYoumightsaythisasldquoIaddaandbthenreturnthemrdquo

4PythonaddsthetwonumbersThenwhenthefunctionendsanylinethatrunsitwillbeabletoassignthisa+bresulttoavariable

AswithmanyotherthingsinthisbookyoushouldtakethisrealslowbreakitdownandtrytotracewhatrsquosgoingonTohelpthereisextracredittosolveapuzzleandlearnsomethingcool

WhatYouShouldSeeClickheretoviewcodeimage

Exercise21Session

$python36ex21py

Letsdosomemathwithjustfunctions

ADDING30+5

SUBTRACTING78-4

MULTIPLYING902

DIVIDING1002

Age35Height74Weight180IQ500

Hereisapuzzle

DIVIDING5002

MULTIPLYING180250

SUBTRACTING74-45000

ADDING35+-44260

Thatbecomes-43910Canyoudoitbyhand

StudyDrills1IfyouarenrsquotreallysurewhatreturndoestrywritingafewofyourownfunctionsandhavethemreturnsomevaluesYoucanreturnanythingthatyoucanputtotherightofan=

2AttheendofthescriptisapuzzleIrsquomtakingthereturnvalueofonefunctionandusingitastheargumentofanotherfunctionIrsquomdoingthisinachainsothatIrsquomkindofcreatingaformulausingthefunctionsItlooks

reallyweirdbutifyourunthescriptyoucanseetheresultsWhatyoushoulddoistrytofigureoutthenormalformulathatwouldrecreatethissamesetofoperations

3OnceyouhavetheformulaworkedoutforthepuzzlegetinthereandseewhathappenswhenyoumodifythepartsofthefunctionsTrytochangeitonpurposetomakeanothervalue

4DotheinverseWriteasimpleformulaandusethefunctionsinthesamewaytocalculateit

ThisexercisemightreallywhackyourbrainoutbuttakeitslowandeasyandtreatitlikealittlegameFiguringoutpuzzleslikethisiswhatmakesprogrammingfunsoIrsquollbegivingyoumorelittleproblemslikethisaswego

CommonStudentQuestionsWhydoesPythonprinttheformulaorthefunctionsldquobackwardrdquoItrsquosnotreallybackwarditrsquosldquoinsideoutrdquoWhenyoustartbreakingdownthefunctionintoseparateformulasandfunctioncallsyoursquollseehowitworksTrytounderstandwhatImeanbyldquoinsideoutrdquoratherthanldquobackwardrdquo

HowcanIuseinput()toentermyownvaluesRememberint(input())Theproblemwiththatisthenyoucanrsquotenterfloatingpointsoalsotryusingfloat(input())instead

WhatdoyoumeanbyldquowriteoutaformulardquoTry24+34100-1023asastartConvertthattousethefunctionsNowcomeupwithyourownsimilarmathequationandusevariablessoitrsquosmorelikeaformula

Exercise22WhatDoYouKnowSoFar

TherewonrsquotbeanycodeinthisexerciseorthenextonesotherersquosnoWhatYouShouldSeeorStudyDrillssectionsInfactthisexerciseislikeonegiantStudyDrillsIrsquomgoingtohaveyoudoareviewofwhatyouhavelearnedsofarFirstgobackthrougheveryexerciseyouhavedonesofarandwritedowneverywordandsymbol(anothernameforldquocharacterrdquo)thatyouhaveusedMakesureyourlistofsymbolsiscompleteNexttoeachwordorsymbolwriteitsnameandwhatitdoesIfyoucanrsquotfindanameforasymbolinthisbookthenlookforitonlineIfyoudonotknowwhatawordorsymboldoesthenreadaboutitagainandtryusingitinsomecodeYoumayrunintoafewthingsyoucanrsquotfindoutorknowsojustkeepthoseonthelistandbereadytolookthemupwhenyoufindthemOnceyouhaveyourlistspendafewdaysrewritingthelistanddouble-checkingthatitrsquoscorrectThismaygetboringbutpushthroughandreallynailitdownOnceyouhavememorizedthelistandwhattheydothenstepitupbywritingouttablesofsymbolstheirnamesandwhattheydofrommemoryIfyouhitsomeyoucanrsquotrecallfrommemorygobackandmemorizethemagain

WarningThemostimportantthingwhendoingthisexerciseisldquoThereisnofailureonlytryingrdquo

WhatYouAreLearningItrsquosimportantwhenyouaredoingaboringmindlessmemorizationexerciselikethistoknowwhyIthelpsyoufocusonagoalandknowthepurposeofallyoureffortsInthisexerciseyouarelearningthenamesofsymbolssothatyoucanreadsourcecodemoreeasilyItrsquossimilartolearningthealphabetandbasicwordsofEnglishexceptthisPythonalphabethasextrasymbolsyoumightnotknowJusttakeitslowanddonothurtyourbrainItrsquosbesttotake15minutesatatimewithyourlistandthentakeabreakGivingyourbrainarestwillhelpyoulearnfasterwithlessfrustration

Exercise23StringsBytesandCharacterEncodings

TodothisexerciseyoursquollneedtodownloadatextfilethatIrsquovewrittennamedlanguagestxt(httpslearnpythonthehardwayorgpython3languagestxt)Thisfilewascreatedwithalistofhumanlanguagestodemonstrateafewinterestingconcepts

1HowmoderncomputersstorehumanlanguagesfordisplayandprocessingandhowPython3callsthisstrings

2HowyoumustldquoencoderdquoandldquodecoderdquoPythonrsquosstringsintoatypecalledbytes

3Howtohandleerrorsinyourstringandbytehandling4Howtoreadcodeandfindoutwhatitmeansevenifyoursquoveneverseenitbefore

InadditiontothatyoursquollalsogetabriefglimpseofthePython3if-statementandlistsforprocessingalistofthingsYoudonrsquothavetomasterthiscodeorunderstandtheseconceptsrightawayYoursquollgetplentyofpracticeinlaterexercisesFornowyourjobistogetatasteofthefutureandlearnthefourtopicsintheprecedinglist

WarningThisexerciseishardTherersquosalotofinformationinitthatyouneedtounderstandanditrsquosinformationthatgoesdeepintocomputersThisexerciseiscomplexbecausePythonrsquosstringsarecomplexanddifficulttouseIrecommendyoutakethisexercisepainfullyslowWritedowneverywordyoudonrsquotunderstandandlookituporresearchitTakeaparagraphatatimeifyoumustYoucancontinuewithotherexerciseswhileyoustudythisonesodonrsquotgetstuckhereJustchipawayatitforaslongasittakes

InitialResearchIrsquomgoingtoteachyouhowtoresearchapieceofcodetoexposeitssecretsYoursquollneedthelanguagestxtfileforthiscodetoworksomakesureyoudownloaditfirstThelanguagestxtfilesimplycontainsalistofhumanlanguagenamesthatareencodedinUTF-8Clickheretoviewcodeimage

ex23py

1importsys

2scriptencodingerror=sysargv

3

4

5defmain(language_fileencodingerrors)

6line=language_filereadline()

7

8ifline

9print_line(lineencodingerrors)

10returnmain(language_fileencodingerrors)

11

12

13defprint_line(lineencodingerrors)

14next_lang=linestrip()

15raw_bytes=next_langencode(encodingerrors=errors)

16cooked_string=raw_bytesdecode(encodingerrors=errors)

17

18print(raw_byteslt===gtcooked_string)

19

20

21languages=open(languagestxtencoding=utf-8)

22

23main(languagesencodingerror)

SimplywritedownalistofeachthingyoursquoveneverseenbeforeTheremaybequiteafewthingsthatarenewsoscanthefileafewtimesOnceyouhavethatyoursquollwanttorunthisPythonscripttoplaywithitHerearesomeexamplecommandsIusedtotestit

WarningYoursquollnoticeIrsquomusingimagesheretoshowyouwhatyoushouldseeAfterextensivetestingitturnsoutthatsomanypeoplehave

seeAfterextensivetestingitturnsoutthatsomanypeoplehavetheircomputersconfiguredtonotdisplayUTF-8thatIhadtouseimagessoyoursquollknowwhattoexpectEvenmyowntypesettingsystem(LaTeX)couldnrsquothandletheseencodingsforcingmetouseimagesinsteadIfyoudonrsquotseethisthenyourTerminalismostlikelynotabletodisplayUTF-8andyoushouldtrytofixthat

Theseexamplesusetheutf-8utf-16andbig5encodingstodemonstratetheconversionandthetypesoferrorsyoucangetEachofthesenamesarecalledaldquocodecrdquoinPython3butyouusetheparameterldquoencodingrdquoAttheendofthisexercisetherersquosalistoftheavailableencodingsifyouwanttotrymoreIrsquollcoverwhatallofthisoutputmeansshortlyYoursquoreonlytryingtogetanideaofhowthisworkssowecantalkaboutitAfteryoursquoverunitafewtimesgothroughyourlistofsymbolsandmakeaguessastowhattheydoWhenyoursquovewrittendownyourguessestrylookingthesymbolsuponlinetoseeifyoucanconfirmyourhypothesesDonrsquotworryifyouhavenoideahowtosearchforthemJustgiveitatry

SwitchesConventionsandEncodingsBeforeIcangetintowhatthiscodemeansyouneedtolearnsomebasicsabouthowdataisstoredinacomputerModerncomputersareincrediblycomplexbutattheircorestheyarelikeahugearrayoflightswitchesComputersuseelectricitytoflipswitchesonoroffTheseswitchescanrepresent1foronor0foroffIntheolddaystherewereallkindsofweirdcomputersthatdidmorethanjust1or0butthesedaysitrsquosjust1sand0sOnerepresentsenergyelectricityonpowersubstanceZerorepresentsoffdonegonepowerdownthelackofenergyWecallthese1sand0sldquobitsrdquoNowacomputerthatonlyletsyouworkwith1and0wouldbebothhorriblyinefficientandincrediblyannoyingComputerstakethese1sand0sandusethemtoencodelargernumbersAtthesmallendacomputerwilluse8ofthese1sand0stoencode256numbers(0-255)WhatdoesldquoencoderdquomeanthoughItrsquosnothingmorethananagreed-uponstandardforhowasequenceofbitsshouldrepresentanumberItrsquosaconventionhumanspickedorstumbledonthatsaysthat00000000wouldbe011111111wouldbe255and00001111wouldbe15TherewereevenhugewarsintheearlyhistoryofcomputersonnothingmorethantheorderofthesebitsbecausetheyweresimplyconventionsweallhadtoagreeonTodaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryone

Todaywecallaldquobyterdquoasequenceof8bits(1sand0s)Intheolddayseveryonehadtheirownconventionforabytesoyoursquollstillrunintopeoplewhothinkthatthistermshouldbeflexibleandhandlesequencesof9bits7bitsor6bitsbutnowwejustsayitrsquos8bitsThatrsquosourconventionandthatconventiondefinesourencodingforabyteTherearefutherconventionsforencodinglargenumbersusing163264andevenmorebitsifyougetintoreallybigmathTherersquosentirestandardsgroupswhodonothingbutargueabouttheseconventionsthenimplementthemasencodingsthateventuallyturnswitchesonandoffOnceyouhavebytesyoucanstarttostoreanddisplaytextbydecidingonanotherconventionforhowanumbermapstoaletterIntheearlydaysofcomputingthereweremanyconventionsthatmapped8or7bits(orlessormore)ontolistsofcharacterskeptinsideacomputerThemostpopularconventionendedupbeingAmericanStandardCodeforInformationInterchangeorASCIIThisstandardmapsanumbertoaletterThenumber90isZwhichinbitsis1011010whichgetsmappedtotheASCIItableinsidethecomputerYoucantrythisoutinPythonrightnow

gtgtgt0b1011010

90

gtgtgtord(Z)

90

gtgtgtchr(90)

Z

gtgtgt

FirstIwritethenumber90inbinarythenIgetthenumberbasedontheletterZthenIconvertthenumbertotheletterZDonrsquotworryaboutneedingtorememberthisthoughIthinkIrsquovehadtodoittwicetheentiretimeIrsquoveusedPythonOncewehavetheASCIIconventionforencodingacharacterusing8bits(abyte)wecanthenldquostringrdquothemtogethertomakeawordIfIwanttowritemynameldquoZedAShawrdquoIjustuseasequenceofbytes[90101100326546328310497119]MostoftheearlytextincomputerswasnothingmorethansequencesofbytesstoredinmemorythatacomputerusedtodisplaytexttoapersonAgainthisisjustasequenceofconventionsthatturnedswitchesonandoffTheproblemwithASCIIisthatitonlyencodesEnglishandmaybeafewothersimilarlanguagesRememberthatabytecanhold256numbers(0-255or

00000000-11111111)Turnsouttherersquosalotmorecharactersthan256usedthroughouttheworldrsquoslanguagesDifferentcountriescreatedtheirownencodingconventionsfortheirlanguagesandthatmostlyworkedbutmanyencodingscouldonlyhandleonelanguageThatmeantifyouwanttoputthetitleofanAmericanEnglishbookinthemiddleofaThaisentenceyouwerekindofintroubleYoursquodneedoneencodingforThaiandoneforEnglishTosolvethisproblemagroupofpeoplecreatedUnicodeItsoundslikeldquoencoderdquoanditismeanttobealdquouniversalencodingrdquoofallhumanlanguagesThesolutionUnicodeprovidesisliketheASCIItablebutitrsquoshugebycomparisonYoucanuse32bitstoencodeaUnicodecharacterandthatismorecharactersthanwecouldpossiblyfindA32-bitnumbermeanswecanstore4294967295characters(2^32)whichisenoughspaceforeverypossiblehumanlanguageandprobablyalotofalienonestooRightnowweusetheextraspaceforimportantthingslikepoopandsmileemojisWenowhaveaconventionforencodinganycharacterswewantbut32bitsis4bytes(328==4)whichmeansthereissomuchwastedspaceinmosttextwewanttoencodeWecanalsouse16bits(2bytes)butstilltherersquosgoingtobewastedspaceinmosttextThesolutionistouseacleverconventiontoencodemostcommoncharactersusing8bitsandthenldquoescaperdquointolargernumberswhenweneedtoencodemorecharactersThatmeanswehaveonemoreconventionthatisnothingmorethanacompressionencodingmakingitpossibleformostcommoncharacterstouse8bitsandthenescapeoutinto16or32bitsasneededTheconventionforencodingtextinPythoniscalledldquoUTF-8rdquowhichmeansldquoUnicodeTransformationFormat8BitsrdquoItisaconventionforencodingUnicodecharactersintosequencesofbyteswhicharesequencesofbitswhichturnsequencesofswitchesonandoffYoucanalsouseotherconventions(encodings)butUTF-8isthecurrentstandard

DisectingtheOutputWecannowlookattheoutputofthecommandsshownpreviouslyLetrsquostakejustthatfirstcommandandthefirstfewlinesofoutput

Theex23pyscriptistakingbyteswritteninsidetheb(bytestring)andconvertingthemtotheUTF-8(orother)encodingyouspecifiedOntheleftisthenumbersforeachbyteoftheUTF-8(showninhexadecimal)andtherighthasthecharacteroutputasactualUTF-8Thewaytothinkofthisistheleftsideoflt===gtisthePythonnumericalbytesortheldquorawrdquobytesPythonusestostorethestringYouspecifythiswithbtotellPythonthisisbytesTheserawbytesarethendisplayedldquocookedrdquoontherightsoyoucanseetherealcharactersinyourTerminal

DisectingtheCodeWehaveanunderstandingofstringsandbytesequencesInPythonastringisaUTF-8encodedsequenceofcharactersfordisplayingorworkingwithtextThebytesarethentheldquorawrdquosequenceofbytesthatPythonusestostorethisUTF-8stringandstartwithabtotellPythonyouareworkingwithrawbytesThisisallbasedonconventionsforhowPythonwantstoworkwithtextHerersquosaPythonsessionshowingmeencodingstringsanddecodingbytes

Allyouneedtorememberisifyouhaverawbytesthenyoumustusedecode()togetthestringRawbyteshavenoconventiontothemTheyarejustsequencesofbyteswithnomeaningotherthannumberssoyoumusttellPythontoldquodecodethisintoaUTFstringrdquoIfyouhaveastringandwanttosenditstoreitshareitordosomeotheroperationthenusuallyitrsquollworkbutsometimesPythonwillthrowupanerrorsayingitdoesnrsquotknowhowtoldquoencoderdquoitAgainPythonknowsitsinternalconventionbutithasnoideawhatconventionyouneedInthatcaseyoumustuseencode()togetthebytesyouneedThewaytorememberthis(eventhoughIlookitupalmosteverytime)istorememberthemnemonicDBESwhichstandsforDecodeBytesEncodeStringsIsayldquodeebessrdquoinmyheadwhenIhavetoconvertbytesandstringsWhenyouhavebytesandneedastringdecodebytesWhenyouhaveastringandneedbytesencodestringsWiththatinmindletrsquosbreakdownthecodeinex23pyline-by-line1ndash2Istartwiththeusualcommandlineargumenthandlingthatyoualready

know5IstartthemainmeatofthiscodeinafunctionconvenientlycalledmainThiswillbecalledattheendofthisscripttogetthingsgoing

6ThefirstthingthisfunctiondoesisreadonelinefromthelanguagesfileitisgivenYouhavedonethisbeforesonothingnewhereJustreadlineasbeforewhendealingwithtextfiles

8IusesomethingnewYouwilllearnaboutthisinthesecondhalfofthebooksoconsiderthisateaserofinterestingthingstocomeThisisanif-statementanditletsyoumakedecisionsinyourPythoncodeYoucantestthetruthofavariableandbasedonthattruthrunapieceofcodeornotrunitInthiscaseIrsquomtestingwhetherlinehassomethinginitThereadlinefunctionwillreturnanemptystringwhenitreachestheendofthefileandiflinesimplytestsforthisemptystringAslongasreadlinegivesussomethingthiswillbetrueandthecodeunder(indentedinlines9ndash10)willrunWhenthisisfalsePythonwillskiplines9ndash10

9IcallaseparatefunctiontodotheactualprintingofthislineThissimplifiesmycodeandmakesiteasierformetounderstanditIfIwanttolearnwhatthisfunctiondoesIcanjumptoitandstudyOnceIknowwhatprint_linedoesIcanattachmymemorytothenameprint_line

andforgetaboutthedetails10IhavewrittenatinyyetpowerfulpieceofmagichereIamcallingmainagaininsidemainActuallyitrsquosnotmagicsincenothingreallyismagicalinprogrammingAlltheinformationyouneedisthereThislookslikeIamcallingthefunctioninsideitselfwhichseemslikeitshouldbeillegaltodoAskyourselfwhyshouldthatbeillegalTherersquosnotechnicalreasonwhyIcanrsquotcallanyfunctionIwantrightthereeventhismainfunctionIfafunctionissimplyajumptothetopwhereIrsquovenameditmainthencallingthisfunctionattheendofitselfwouldjumpbacktothetopandrunitagainThatwouldmakeitloopNowlookbackatline8andyoursquollseetheif-statementkeepsthisfunctionfromloopingforeverCarefullystudythisbecauseitisasignificantconceptbutdonrsquotworryifyoucanrsquotgraspitrightaway

13Istartthedefinitionfortheprint_linefunctionwhichdoestheactualencodingofeachlinefromthelanguagestxtfile

14Thisisasimplestrippingofthetrailingnonthelinestring15IfinallytakethelanguageIrsquovereceivedfromthelanguagestxtfileandencodeitintotherawbytesRemembertheDBESmnemonicDecodebytesencodestringsThenext_langvariableisastringsotogettherawbytesImustcallencode()onittoencodestringsIpasstoencode()theencodingIwantandhowtohandleerrors

16Idotheextrastepofshowingtheinverseofline15bycreatingacooked_stringvariablefromtheraw_bytesRememberDBESsaysIdecodebytesandraw_bytesisbytessoIcalldecode()onittogetaPythonstringThisstringshouldbethesameasthenext_langvariable

18Isimplyprintthembothouttoshowyouwhattheylooklike21IrsquomdonedefiningfunctionssonowIwanttoopenthelanguagestxtfile

23Theendofthescriptsimplyrunsthemainfunctionwithallthecorrectparameterstogeteverythinggoingandkick-starttheloopRememberthatthisthenjumpstowherethemainfunctionisdefinedonline5andonline10mainiscalledagaincausingthistokeeploopingTheiflineonline8willpreventourloopfromgoingforever

EncodingsDeepDive

WecannowuseourlittlescripttoexploreotherencodingsThefollowingshowsmeplayingwithdifferentencodingsandseeinghowtobreakthemFirstIrsquomdoingasimpleUTF-16encodingsoyoucanseehowitchangescomparedtoUTF-8YoucanalsouseUTF-32toseehowthatrsquosevenbiggerandgetanideaofthespacesavedwithUTF-8AfterthatItryBig5andyoursquollseethatPythondoesnotlikethatatallItthrowsupanerrorthatBig5canrsquotencodesomeofthecharactersatposition0(whichissuperhelpful)OnesolutionistotellPythontoldquoreplacerdquoanybadcharactersfortheBig5encodingThatrsquosthenextexampleandyoursquollseeitputsacharacterwhereveritfindsacharacterthatdoesnrsquotmatchtheBig5encodingsystem

BreakingItRoughideasincludethefollowing

1Findstringsoftextencodedinotherencodingsandplacethemintheex23pyfiletoseehowitbreaks

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist

2Findoutwhathappenswhenyougiveanencodingthatdoesnrsquotexist3ExtrachallengingRewritethisusingthebbytesinsteadoftheUTF-8stringseffectivelyreversingthescript

4IfyoucandothatthenyoucanalsobreakthesebytesbyremovingsometoseewhathappensHowmuchdoyouneedtoremovetocausePythontobreakHowmuchcanyouremovetodamagethestringoutputbutpassPythonrsquosdecodingsystem

5Usewhatyoulearnedfromitem4toseeifyoucanmanglethefilesWhaterrorsdoyougetHowmuchdamagecanyoucauseandgetthefilepastPythonrsquosdecodingsystem

Exercise24MorePractice

YouaregettingtotheendofthissectionYoushouldhaveenoughPythonldquounderyourfingersrdquotomoveontolearningabouthowprogrammingreallyworksbutyoushoulddosomemorepracticeThisexerciseislongerandallaboutbuildingupstaminaThenextexercisewillbesimilarDothemgetthemexactlyrightanddoyourchecksClickheretoviewcodeimage

ex24py

1print(Letspracticeeverything)

2print(Youdneedtoknowboutescapeswiththatdo)

3print(nnewlinesandttabs)

4

5poem=

6tThelovelyworld

7withlogicsofirmlyplanted

8cannotdiscernntheneedsoflove

9norcomprehendpassionfromintuition

10andrequiresanexplanation

11nttwherethereisnone

12

13

14print(--------------)

15print(poem)

16print(--------------)

17

18

19five=10-2+3-6

20print(fThisshouldbefivefive)

21

22defsecret_formula(started)

23jelly_beans=started500

24jars=jelly_beans1000

25crates=jars100

26returnjelly_beansjarscrates

27

28

29start_point=10000

30beansjarscrates=secret_formula(start_point)

31

32rememberthatthisisanotherwaytoformatastring

33print(Withastartingpointofformat(start_point))

34itsjustlikewithanfstring

35print(fWedhavebeansbeansjarsjarsandcrates

crates)

36

37start_point=start_point10

38

39print(Wecanalsodothatthisway)

40formula=secret_formula(start_point)

41thisisaneasywaytoapplyalisttoaformatstring

42print(Wedhavebeansjarsand

cratesformat(formula))

WhatYouShouldSeeClickheretoviewcodeimage

Exercise24Session

$python36ex24py

Letspracticeeverything

Youdneedtoknowboutescapeswiththatdo

newlinesandtabs

--------------

Thelovelyworld

withlogicsofirmlyplanted

cannotdiscern

theneedsoflove

norcomprehendpassionfromintuition

andrequiresanexplanation

wherethereisnone

--------------

Thisshouldbefive5

Withastartingpointof10000

Wedhave5000000beans50000jarsand500crates

Wecanalsodothatthisway

Wedhave5000000beans5000jarsand50crates

StudyDrills1Makesuretodoyourchecksreaditbackwardreaditoutloudandputcommentsaboveconfusingparts

2BreakthefileonpurposethenrunittoseewhatkindsoferrorsyougetMakesureyoucanfixit

CommonStudentQuestionsWhydoyoucallthevariablejelly_beansbutthenamebeanslaterThatrsquospartofhowafunctionworksRememberthatinsidethefunctionthevariableistemporaryWhenyoureturnitthenitcanbeassignedtoavariableforlaterIrsquomjustmakinganewvariablenamedbeanstoholdthereturnvalue

WhatdoyoumeanbyreadingthecodebackwardStartatthelastlineComparethatlineinyourfiletothesamelineinmineOnceitrsquosexactlythesamemoveuptothenextlineDothisuntilyougettothefirstlineofthefile

WhowrotethatpoemIdidNotallofmypoemssuck

Exercise25EvenMorePractice

WersquoregoingtodosomemorepracticeinvolvingfunctionsandvariablestomakesureyouknowthemwellThisexerciseshouldbestraightforwardforyoutotypeinbreakdownandunderstandHoweverthisexerciseisalittledifferentYouwonrsquotberunningitInsteadyouwillimportitintoPythonandrunthefunctionsyourselfClickheretoviewcodeimage

ex25py

1defbreak_words(stuff)

2Thisfunctionwillbreakupwordsforus

3words=stuffsplit()

4returnwords

5

6defsort_words(words)

7Sortsthewords

8returnsorted(words)

9

10defprint_first_word(words)

11Printsthefirstwordafterpoppingitoff

12word=wordspop(0)

13print(word)

14

15defprint_last_word(words)

16Printsthelastwordafterpoppingitoff

17word=wordspop(-1)

18print(word)

19

20defsort_sentence(sentence)

21Takesinafullsentenceandreturnsthesorted

words

22words=break_words(sentence)

23returnsort_words(words)

24

25defprint_first_and_last(sentence)

26Printsthefirstandlastwordsofthesentence

27words=break_words(sentence)

28print_first_word(words)

29print_last_word(words)

30

31defprint_first_and_last_sorted(sentence)

32Sortsthewordsthenprintsthefirstandlastone

33words=sort_sentence(sentence)

34print_first_word(words)

35print_last_word(words)Firstrunthiswithpython36

ex25pytofindanyerrorsyouhavemadeOnceyouhavefoundallof

theerrorsyoucanandfixedthemyouwillthenwanttofollowthe

WhatYouShouldSeesectiontocompletetheexercise

WhatYouShouldSeeInthisexercisewersquoregoingtointeractwithyourex25pyfileinsidethepython36interpreteryouusedperiodicallytodocalculationsYourunpython36fromtheTerminallikethisClickheretoviewcodeimage

$python36

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtYouroutputshouldlooklikemineandafterthegtcharacter

(calledtheprompt)youcantypePythoncodeinanditwillrun

immediatelyUsingthisIwantyoutotypeeachoftheselinesof

Pythoncodeintopython36andseewhatitdoesClickheretoview

codeimage

Exercise25PythonSession

1importex25

2sentence=Allgoodthingscometothosewhowait

3words=ex25break_words(sentence)

4words

5sorted_words=ex25sort_words(words)

6sorted_words

7ex25print_first_word(words)

8ex25print_last_word(words)

9words

10ex25print_first_word(sorted_words)

11ex25print_last_word(sorted_words)

12sorted_words

13sorted_words=ex25sort_sentence(sentence)

14sorted_words

15ex25print_first_and_last(sentence)

16ex25print_first_and_last_sorted(sentence)Herersquoswhatitlooks

likewhenIworkwiththeex25pymoduleinpython36Clickhereto

viewcodeimage

Exercise25PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtimportex25

gtgtgtsentence=Allgoodthingscometothosewhowait

gtgtgtwords=ex25break_words(sentence)

gtgtgtwords

[Allgoodthingscometothosewhowait]

gtgtgtsorted_words=ex25sort_words(words)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_word(words)

All

gtgtgtex25print_last_word(words)

wait

gtgtgtwords

[goodthingscometothosewho]

gtgtgtex25print_first_word(sorted_words)

All

gtgtgtex25print_last_word(sorted_words)

who

gtgtgtsorted_words

[comegoodthingsthosetowait]

gtgtgtsorted_words=ex25sort_sentence(sentence)

gtgtgtsorted_words

[Allcomegoodthingsthosetowaitwho]

gtgtgtex25print_first_and_last(sentence)

All

wait

gtgtgtex25print_first_and_last_sorted(sentence)

All

whoAsyougothrougheachoftheselinesmakesureyoucanfindthe

functionthatrsquosbeingruninex25pyandunderstandhoweachone

worksIfyougetdifferentresultsorerroryoursquollhavetogofix

yourcodeexitpython36andstartover

StudyDrills1TaketheremaininglinesoftheWhatYouShouldSeeoutputandfigureoutwhattheyaredoingMakesureyouunderstandhowyouarerunningyourfunctionsintheex25module

2Trydoingthishelp(ex25)andalsohelp(ex25break_words)Noticehowyougethelpforyourmoduleandhowthehelpisthoseoddstringsyouputaftereachfunctioninex25Thosespecialstringsarecalleddocumentationcommentsandwersquollbeseeingmoreofthem

3Typingex25isannoyingAshortcutistodoyourimportlikethisfromex25importThisislikesayingldquoImporteverythingfromex25rdquoProgrammerslikesayingthingsbackwardStartanewsessionandseehowallyourfunctionsarerightthere

4TrybreakingyourfileandseewhatitlookslikeinpythonwhenyouuseitYouwillhavetoquitpythonwithquit()tobeabletoreloadit

CommonStudentQuestionsIgetNoneprintedoutforsomeofthefunctionsYouprobablyhaveafunctionthatismissingthereturnattheendGobackwardthroughthefileandconfirmthateverylineisright

Iget-bashimportcommandnotfoundwhenItypeimportex25PayattentiontowhatIrsquomdoingintheWhatYouShouldSeesectionIrsquomdoingthisinPythonnotintheTerminalThatmeansyoufirstrunPython

IgetImportErrorNomodulenamedex25pywhenItypeimportex25pyDonrsquotaddthepytotheendPythonknowsthefileendsinpysoyoujusttypeimportex25

IgetSyntaxErrorinvalidsyntaxwhenIrunthisThatmeansyouhavesomethinglikeamissing(ororsimilarsyntaxerroronthatlineoraboveitAnytimeyougetthaterrorstartatthelineitmentionsandcheckthatitrsquosrightthengobackwardcheckingeachlineabovethat

HowcanthewordspopfunctionchangethewordsvariableThatrsquosacomplicatedquestionbutinthiscasewordsisalistandbecauseofthatyoucangiveitcommandsanditrsquollretaintheresultsofthosecommandsThisissimilartohowfilesandmanyotherthingsworkedwhenyouwereworkingwiththem

WhenshouldIprintinsteadofreturninafunctionThereturnfromafunctiongivesthelineofcodethatcalledthefunctionaresultYoucanthinkofafunctionastakinginputthroughitsargumentsandreturningoutputthroughreturnTheprintiscompletelyunrelatedtothisandonlydealswithprintingoutputtotheTerminal

Exercise26CongratulationsTakeaTest

YouarealmostdonewiththefirsthalfofthebookThesecondhalfiswherethingsgetinterestingYouwilllearnlogicandbeabletodousefulthingslikemakedecisionsBeforeyoucontinueIhaveaquizforyouThisquizwillbeveryhardbecauseitrequiresyoutofixsomeoneelsersquoscodeWhenyouareaprogrammeryouoftenhavetodealwithotherprogrammersrsquocodemdashandalsowiththeirarroganceProgrammerswillveryfrequentlyclaimthattheircodeisperfectTheseprogrammersarestupidpeoplewhocarelittleforothersAgoodprogrammerassumeslikeagoodscientistthattherersquosalwayssomeprobabilitytheircodeiswrongGoodprogrammersstartfromthepremisethattheirsoftwareisbrokenandthenworktoruleoutallpossiblewaysitcouldbewrongbeforefinallyadmittingthatmaybeitreallyistheotherguyrsquoscodeInthisexerciseyouwillpracticedealingwithabadprogrammerbyfixingabadprogrammerrsquoscodeIhavepoorlycopiedExercises24and25intoafileandremovedrandomcharactersandaddedflawsMostoftheerrorsarethingsPythonwilltellyouwhilesomeofthemarematherrorsyoushouldfindOthersareformattingerrorsorspellingmistakesinthestringsAlloftheseerrorsareverycommonmistakesallprogrammersmakemdashevenexperiencedonesYourjobinthisexerciseistocorrectthisfileUseallofyourskillstomakethisfilebetterAnalyzeitfirstmaybeprintingitouttoedititlikeyouwouldaschooltermpaperFixeachflawandkeeprunningitandfixingituntilthescriptrunsperfectlyTrynottogethelpIfyougetstucktakeabreakandcomebacktoitlaterEvenifthistakesdaystodobustthroughitandmakeitrightThepointofthisexerciseisnrsquottotypeitinbuttofixanexistingfileTodothatyoumustgotohttplearnpythonthehardwayorgpython3exercise26txtCopy-pastethecodeintoafilenamedex26pyThisistheonlytimeyouareallowedtocopy-paste

CommonStudentQuestionsDoIhavetoimportex25pyorcanIjustremovethereferencestoitYoucandoeitherThisfilehasthefunctionsfromex25

thoughsofirstgowithremovingreferencestoitCanIrunthecodewhileIrsquomfixingitYoumostcertainlymayThecomputeristheretohelpsouseitasmuchaspossible

Exercise27MemorizingLogic

TodayisthedayyoustartlearningaboutlogicUptothispointyouhavedoneeverythingyoupossiblycanreadingandwritingfilestotheTerminalandhavelearnedquitealotofthemathcapabilitiesofPythonFromnowonyouwillbelearninglogicYouwonrsquotlearncomplextheoriesthatacademicslovetostudybutjustthebasiclogicthatmakesrealprogramsworkandthatrealprogrammersneedeverydayLearninglogichastocomeafteryoudosomememorizationIwantyoutodothisexerciseforanentireweekDonotfalterEvenifyouareboredoutofyourmindkeepdoingitThisexercisehasasetoflogictablesyoumustmemorizetomakeiteasierforyoutodothelaterexercisesIrsquomwarningyouthiswonrsquotbefunatfirstItwillbedownrightboringandtediousbutthisteachesyouaveryimportantskillyouwillneedasaprogrammerYouwillneedtobeabletomemorizeimportantconceptsinyourlifeMostoftheseconceptswillbeexcitingonceyougetthemYouwillstrugglewiththemlikewrestlingasquidthenonedayyouwillunderstanditAllthatworkmemorizingthebasicspaysoffbiglaterHerersquosatiponhowtomemorizesomethingwithoutgoinginsaneDoatinybitatatimethroughoutthedayandmarkdownwhatyouneedtoworkonmostDonottrytositdownfortwohoursstraightandmemorizethesetablesThiswonrsquotworkYourbrainwillonlyretainwhateveryoustudiedinthefirst15or30minutesanywayInsteadcreateabunchofindexcardswitheachcolumnontheleft(TrueorFalse)onthefrontandthecolumnontherightonthebackYoushouldthentakethemoutseetheldquoTrueorFalserdquoandimmediatelysayldquoTruerdquoKeeppracticinguntilyoucandothisOnceyoucandothatstartwritingoutyourowntruthtableseachnightintoanotebookDonotjustcopythemTrytodothemfrommemoryWhenyougetstuckglancequicklyattheonesIhaveheretorefreshyourmemoryDoingthiswilltrainyourbraintorememberthewholetableDonotspendmorethanoneweekonthisbecauseyouwillbeapplyingitasyougo

TheTruthTermsInPythonwehavethefollowingterms(charactersandphrases)fordeterminingifsomethingisldquoTruerdquoorldquoFalserdquoLogiconacomputerisallaboutseeingifsomecombinationofthesecharactersandsomevariablesisTrueatthatpointin

somecombinationofthesecharactersandsomevariablesisTrueatthatpointintheprogram

bullandbullorbullnotbull=(notequal)bull==(equal)bullgt=(greater-than-equal)bulllt=(less-than-equal)bullTruebullFalse

YouactuallyhaverunintothesecharactersbeforebutmaybenotthetermsTheterms(andornot)actuallyworkthewayyouexpectthemtojustlikeinEnglish

TheTruthTablesWewillnowusethesecharacterstomakethetruthtablesyouneedtomemorize

NowusethesetablestowriteupyourowncardsandspendtheweekmemorizingthemRememberthoughthereisnofailinginthisbookjusttryingashardasyoucaneachdayandthenalittlebitmore

CommonStudentQuestionsCanrsquotIjustlearntheconceptsbehindBooleanalgebraandnotmemorizethisSureyoucandothatbutthenyoursquollhavetoconstantlygothroughtherulesforBooleanalgebrawhileyoucodeIfyoumemorizethesefirstitnotonlybuildsyourmemorizationskillsitalsomakestheseoperationsnaturalAfterthattheconceptofBooleanalgebraiseasyButdowhateverworksforyou

Exercise28BooleanPractice

ThelogiccombinationsyoulearnedfromthelastexercisearecalledBooleanlogicexpressionsBooleanlogicisusedeverywhereinprogrammingItisafundamentalpartofcomputationandknowingtheexpressionsisakintoknowingyourscalesinmusicInthisexerciseyouwilltakethelogicexercisesyoumemorizedandstarttryingthemoutinPythonTakeeachoftheselogicproblemsandwritewhatyouthinktheanswerwillbeIneachcaseitwillbeeitherTrueorFalseOnceyouhavetheanswerswrittendownstartPythoninyourTerminalandtypeeachlogicproblemintoconfirmyouranswers

1TrueandTrue2FalseandTrue31==1and2==14test==test51==1or2=16Trueand1==17Falseand0=08Trueor1==19test==testing101=0and2==111test=testing12test==113not(TrueandFalse)14not(1==1and0=1)15not(10==1or1000==1000)16not(1=10or3==4)17not(testing==testingandZed==CoolGuy)

181==1and(not(testing==1or1==0))19chunky==baconand(not(3==4or3==3))203==3and(not(testing==testingor

Python==Fun))

IwillalsogiveyouatricktohelpyoufigureoutthemorecomplicatedonestowardtheendWheneveryouseetheseBooleanlogicstatementsyoucansolvethemeasilybythissimpleprocess1Findanequalitytest(==or=)andreplaceitwithitstruth

2Findeachandorinsideparenthesesandsolvethosefirst3Findeachnotandinvertit4Findanyremainingandorandsolveit5WhenyouaredoneyoushouldhaveTrueorFalse

Iwilldemonstratewithavariationonitem20Clickheretoviewcodeimage

3=4andnot(testing=testorPython==Python)

HerersquosmegoingthrougheachofthestepsandshowingyouthetranslationuntilIrsquoveboileditdowntoasingleresult1Solveeachequalitytest

3=4isTrueTrueandnot(testing=testorPython==Python)

testing=testisTrueTrueandnot(TrueorPython==Python)

Python==PythonTrueandnot(TrueorTrue)2Findeachandorinparentheses()(TrueorTrue)isTrueTrueandnot(True)

3Findeachnotandinvertitnot(True)isFalseTrueandFalse4FindanyremainingandorsandsolvethemTrueandFalseisFalse

WiththatwersquoredoneandknowtheresultisFalse

WarningThemorecomplicatedonesmayseemveryhardatfirstYoushouldbeabletotakeagoodfirststabatsolvingthembutdonotgetdiscouragedIrsquomjustgettingyouprimedformoreoftheseldquologicgymnasticsrdquosothatlatercoolstuffismucheasierJuststickwithitandkeeptrackofwhatyougetwrongbutdonotworrythatitrsquosnotgettinginyourheadquiteyetItrsquollcome

WhatYouShouldSeeAfteryouhavetriedtoguessatthesethisiswhatyoursessionwithPythonmightlooklikeClickheretoviewcodeimage

$python36

Python251(r25154863Feb62009190212)

[GCC401(AppleIncbuild5465)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtTrueandTrue

True

gtgtgt1==1and2==2

True

StudyDrills1TherearealotofoperatorsinPythonsimilarto=and==TrytofindasmanyldquoequalityoperatorsrdquoasyoucanTheyshouldbelikeltorlt=

2WriteoutthenamesofeachoftheseequalityoperatorsForexampleIcall=ldquonotequalrdquo

3PlaywithPythonbytypingoutnewBooleanoperatorsandbeforeyoupressEntertrytoshoutoutwhatitisDonotthinkaboutitShoutthefirstthingthatcomestomindWriteitdownthenpressEnterandkeeptrackofhowmanyyougetrightandwrong

4Throwawaythepieceofpaperfrom3soyoudonotaccidentallytrytouseitlater

CommonStudentQuestionsWhydoestestandtestreturntestor1and1return1insteadofTruePythonandmanylanguagesliketoreturnoneoftheoperandstotheirBooleanexpressionsratherthanjustTrueorFalseThismeansthatifyoudidFalseand1yougetthefirstoperand(False)butifyoudoTrueand1yougetthesecond(1)Playwiththisabit

Isthereanydifferencebetween=andltgtPythonhasdeprecatedltgtinfavorof=souse=Otherthanthatthereshouldbenodifference

IsnrsquotthereashortcutYesAnyandexpressionthathasaFalseisimmediatelyFalsesoyoucanstopthereAnyorexpressionthathasaTrueisimmediatelyTruesoyoucanstopthereButmakesurethatyoucanprocessthewholeexpressionbecauselateritbecomeshelpful

Exercise29WhatIf

HereisthenextscriptofPythonyouwillenterwhichintroducesyoutotheif-statementTypethisinmakeitrunexactlyrightandthenwersquollseeifyourpracticehaspaidoffClickheretoviewcodeimage

ex29py

1people=20

2cats=30

3dogs=15

4

5

6ifpeopleltcats

7print(ToomanycatsTheworldisdoomed)

8

9ifpeoplegtcats

10print(NotmanycatsTheworldissaved)

11

12ifpeopleltdogs

13print(Theworldisdrooledon)

14

15ifpeoplegtdogs

16print(Theworldisdry)

17

18

19dogs+=5

20

21ifpeoplegt=dogs

22print(Peoplearegreaterthanorequaltodogs)

23

24ifpeoplelt=dogs

25print(Peoplearelessthanorequaltodogs)

26

27

28ifpeople==dogs

29print(Peoplearedogs)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise29Session

$python36ex29py

ToomanycatsTheworldisdoomed

Theworldisdry

Peoplearegreaterthanorequaltodogs

Peoplearelessthanorequaltodogs

Peoplearedogs

StudyDrillsInthisStudyDrilltrytoguesswhatyouthinktheif-statementisandwhatitdoesTrytoanswerthesequestionsinyourownwordsbeforemovingontothenextexercise

1Whatdoyouthinktheifdoestothecodeunderit2Whydoesthecodeundertheifneedtobeindentedfourspaces3Whathappensifitisnrsquotindented4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryit

5Whathappensifyouchangetheinitialvaluesforpeoplecatsanddogs

CommonStudentQuestionsWhatdoes+=meanThecodex+=1isthesameasdoingx=x+1butinvolveslesstypingYoucancallthistheldquoincrementbyrdquooperatorThesamegoesfor-=andmanyotherexpressionsyoursquolllearnlater

Exercise30ElseandIf

Inthelastexerciseyouworkedoutsomeif-statementsandthentriedtoguesswhattheyareandhowtheyworkBeforeyoulearnmoreIrsquollexplainwhateverythingisbyansweringthequestionsyouhadfromthepreviousStudyDrillssectionYoudidtheStudyDrillsright

1WhatdoyouthinktheifdoestothecodeunderitAnif-statementcreateswhatiscalledaldquobranchrdquointhecodeItrsquoskindoflikethosechooseyourownadventurebookswhereyouareaskedtoturntoonepageifyoumakeonechoiceandanotherifyougoadifferentdirectionTheif-statementtellsyourscriptldquoIfthisBooleanexpressionisTruethenrunthecodeunderitotherwiseskipitrdquo

2WhydoesthecodeundertheifneedtobeindentedfourspacesAcolonattheendofalineishowyoutellPythonyouaregoingtocreateanewldquoblockrdquoofcodeandthenindentingfourspacestellsPythonwhatlinesofcodeareinthatblockThisisexactlythesamethingyoudidwhenyoumadefunctionsinthefirsthalfofthebook

3WhathappensifitisnrsquotindentedIfitisnrsquotindentedyouwillmostlikelycreateaPythonerrorPythonexpectsyoutoindentsomethingafteryouendalinewitha(colon)

4CanyouputotherBooleanexpressionsfromExercise27intheif-statementTryitYesyoucanandtheycanbeascomplexasyoulikealthoughreallycomplexthingsgenerallyarebadstyle

5WhathappensifyouchangetheinitialvaluesforpeoplecatsanddogsBecauseyouarecomparingnumbersifyouchangethenumbersdifferentif-statementswillevaluatetoTrueandtheblocksofcodeunderthemwillrunGobackandputdifferentnumbersinandseeifyoucanfigureoutinyourheadwhichblocksofcodewillrun

ComparemyanswerstoyouranswersandmakesureyoureallyunderstandtheconceptofaldquoblockrdquoofcodeThisisimportantforwhenyoudothenextexercisewhereyouwriteallthepartsofif-statementsthatyoucanuseTypethisoneinandmakeitworktooClickheretoviewcodeimage

ex30py

1people=30

2cars=40

3trucks=15

4

5

6ifcarsgtpeople

7print(Weshouldtakethecars)

8elifcarsltpeople

9print(Weshouldnottakethecars)

10else

11print(Wecantdecide)

12

13iftrucksgtcars

14print(Thatstoomanytrucks)

15eliftrucksltcars

16print(Maybewecouldtakethetrucks)

17else

18print(Westillcantdecide)

19

20ifpeoplegttrucks

21print(Alrightletsjusttakethetrucks)

22else

23print(Fineletsstayhomethen)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise30Session

$python36ex30py

Weshouldtakethecars

Maybewecouldtakethetrucks

Alrightletsjusttakethetrucks

StudyDrills1Trytoguesswhatelifandelsearedoing2Changethenumbersofcarspeopleandtrucksandthentracethrougheachif-statementtoseewhatwillbeprinted

3TrysomemorecomplexBooleanexpressionslikecarsgtpeopleortrucksltcars

4Aboveeachlinewriteacommentdescribingwhatthelinedoes

CommonStudentQuestions

CommonStudentQuestionsWhathappensifmultipleelifblocksareTruePythonstartsatthetopandrunsthefirstblockthatisTruesoitwillrunonlythefirstone

Exercise31MakingDecisions

InthefirsthalfofthisbookyoumostlyjustprintedoutstringsandcalledfunctionsbuteverythingwasbasicallyinastraightlineYourscriptsranstartingatthetopandwenttothebottomwheretheyendedIfyoumadeafunctionyoucouldrunthatfunctionlaterbutitstilldidnrsquothavethekindofbranchingyouneedtoreallymakedecisionsNowthatyouhaveifelseandelifyoucanstarttomakescriptsthatdecidethingsInthelastscriptyouwroteoutasimplesetoftestsaskingsomequestionsInthisscriptyouwillasktheuserquestionsandmakedecisionsbasedontheiranswersWritethisscriptandthenplaywithitquitealottofigureitoutClickheretoviewcodeimage

ex31py

1print(Youenteradarkroomwithtwodoors

2Doyougothroughdoor1ordoor2)

3

4door=input(gt)

5

6ifdoor==1

7print(Theresagiantbearhereeatingacheesecake)

8print(Whatdoyoudo)

9print(1Takethecake)

10print(2Screamatthebear)

11

12bear=input(gt)

13

14ifbear==1

15print(ThebeareatsyourfaceoffGoodjob)

16elifbear==2

17print(ThebeareatsyourlegsoffGoodjob)

18else

19print(fWelldoingbearisprobablybetter)

20print(Bearrunsaway)

21

22elifdoor==2

23print(YoustareintotheendlessabyssatCthulhus

retina)

24print(1Blueberries)

25print(2Yellowjacketclothespins)

26print(3Understandingrevolversyellingmelodies)

27

28insanity=input(gt)

29

30ifinsanity==1orinsanity==2

31print(Yourbodysurvivespoweredbyamindofjello)

32print(Goodjob)

33else

34print(Theinsanityrotsyoureyesintoapoolof

muck)

35print(Goodjob)

36

37else

38print(YoustumblearoundandfallonaknifeanddieGood

job)Akeypointhereisthatyouarenowputtingtheif-statements

insideif-statementsascodethatcanrunThisisverypowerfuland

canbeusedtocreateldquonestedrdquodecisionswhereonebranchleadsto

anotherandanother

Makesureyouunderstandthisconceptofif-statementsinsideif-statementsInfactdotheStudyDrillstoreallynailit

WhatYouShouldSeeHereismeplayingthislittleadventuregameIdonotdosowellClickheretoviewcodeimage

Exercise31Session

$python36ex31py

Youenteradarkroomwithtwodoors

Doyougothroughdoor1ordoor2

gt1

Theresagiantbearhereeatingacheesecake

Whatdoyoudo

1Takethecake

2Screamatthebear

gt2

ThebeareatsyourlegsoffGoodjob

StudyDrills1MakenewpartsofthegameandchangewhatdecisionspeoplecanmakeExpandthegameoutasmuchasyoucanbeforeitgetsridiculous

2WriteacompletelynewgameMaybeyoudonrsquotlikethisonesomakeyourownThisisyourcomputerdowhatyouwant

CommonStudentQuestions

CommonStudentQuestionsCanyoureplaceelifwithasequenceofif-elsecombinationsYoucaninsomesituationsbutitdependsonhoweachifelseiswrittenItalsomeansthatPythonwillcheckeveryif-elsecombinationratherthanjustthefirstfalseoneslikeitwouldwithif-elif-elseTrytomakesomeofthesetofigureoutthedifferences

HowdoItellwhetheranumberisbetweenarangeofnumbersYouhavetwooptionsUse0ltxlt10or1lt=xlt10whichisclassicnotationorusexinrange(110)

WhatifIwantedmoreoptionsintheif-elif-elseblocksAddmoreelifblocksforeachpossiblechoice

Exercise32LoopsandLists

YoushouldnowbeabletodosomeprogramsthataremuchmoreinterestingIfyouhavebeenkeepingupyoushouldrealizethatnowyoucancombinealltheotherthingsyouhavelearnedwithif-statementsandBooleanexpressionstomakeyourprogramsdosmartthingsHoweverprogramsalsoneedtodorepetitivethingsveryquicklyWearegoingtouseafor-loopinthisexercisetobuildandprintvariouslistsWhenyoudotheexerciseyouwillstarttofigureoutwhattheyareIwonrsquottellyourightnowYouhavetofigureitoutBeforeyoucanuseafor-loopyouneedawaytostoretheresultsofloopssomewhereThebestwaytodothisiswithlistsAlistisexactlywhatthenamesaysacontainerofthingsthatareorganizedinorderfromfirsttolastItrsquosnotcomplicatedyoujusthavetolearnanewsyntaxFirstherersquoshowyoumakelistsClickheretoviewcodeimage

hairs=[brownblondred]

eyes=[brownbluegreen]

weights=[1234]

Youstartthelistwiththe[(leftbracket)whichldquoopensrdquothelistThenyouputeachitemyouwantinthelistseparatedbycommassimilartofunctionargumentsLastlyendthelistwitha](rightbracket)toindicatethatitrsquosoverPythonthentakesthislistandallitscontentsandassignsthemtothevariable

WarningThisiswherethingsgettrickyforpeoplewhocanrsquotcodeYourbrainhasbeentaughtthattheworldisflatRememberinthelastexercisewhereyouputif-statementsinsideif-statementsThatprobablymadeyourbrainhurtbecausemostpeopledonotponderhowtoldquonestrdquothingsinsidethingsInprogrammingnestedstructuresareallovertheplaceYouwillfindfunctionsthatcallotherfunctionsthathaveif-statementsthathavelistswithlistsinsidelistsIfyouseeastructurelikethisthatyoucanrsquotfigureouttakeoutapencilandpaperandbreakitdownmanuallybitbybituntilyouunderstandit

Wenowwillbuildsomelistsusingsomefor-loopsandprintthemoutClickheretoviewcodeimage

ex32py

1the_count=[12345]

2fruits=[applesorangespearsapricots]

3change=[1pennies2dimes3quarters]

4

5thisfirstkindoffor-loopgoesthroughalist

6fornumberinthe_count

7print(fThisiscountnumber)

8

9sameasabove

10forfruitinfruits

11print(fAfruitoftypefruit)

12

13alsowecangothroughmixedliststoo

14noticewehavetousesincewedontknowwhatsinit

15foriinchange

16print(fIgoti)

17

18wecanalsobuildlistsfirststartwithanemptyone

19elements=[]

20

21thenusetherangefunctiontodo0to5counts

22foriinrange(06)

23print(fAddingitothelist)

24appendisafunctionthatlistsunderstand

25elementsappend(i)

26

27nowwecanprintthemouttoo

28foriinelements

29print(fElementwasi)

WhatYouShouldSee

Exercise32Session

$python36ex32py

Thisiscount1

Thisiscount2

Thisiscount3

Thisiscount4

Thisiscount5

Afruitoftypeapples

Afruitoftypeoranges

Afruitoftypepears

Afruitoftypeapricots

Igot1

Igotpennies

Igot2

Igotdimes

Igot3

Igotquarters

Adding0tothelist

Adding1tothelist

Adding2tothelist

Adding3tothelist

Adding4tothelist

Adding5tothelist

Elementwas0

Elementwas1

Elementwas2

Elementwas3

Elementwas4

Elementwas5

StudyDrills1TakealookathowyouusedrangeLookuptherangefunctiontounderstandit

2Couldyouhaveavoidedthatfor-loopentirelyonline22andjustassignedrange(06)directlytoelements

3FindthePythondocumentationonlistsandreadaboutthemWhatotheroperationscanyoudotolistsbesidesappend

CommonStudentQuestionsHowdoyoumakea2-dimensional(2D)listThatrsquosalistinalistlikethis[[123][456]]

ArenrsquotlistsandarraysthesamethingThatdependsonthelanguageandtheimplementationInclassictermsalistisverydifferentfromanarraybecauseofhowtheyrsquoreimplementedInRubythoughtheycallthesearraysInPythontheycallthemlistsJustcalltheselistsfornowsincethatrsquoswhatPythoncallsthem

Whyisafor-loopabletouseavariablethatisnrsquotdefinedyetThevariableisdefinedbythefor-loopwhenitstartsinitializingittothecurrentelementoftheloopiterationeachtimethrough

Whydoesforiinrange(13)onlylooptwotimesinsteadofthreetimesTherange()functiononlydoesnumbersfromthefirsttothelastnotincludingthelastSoitstopsattwonotthreeintheprecedingThisturnsouttobethemostcommonwaytodothiskindofloop

Whatdoeselementsappend()doItsimplyappendstotheendofthelistOpenupthePythonshellandtryafewexampleswithalistyoumakeAnytimeyourunintothingslikethisalwaystrytoplaywiththeminteractivelyinthePythonshell

Exercise33WhileLoops

Nowtototallyblowyourmindwithanewloopthewhile-loopAwhile-loopwillkeepexecutingthecodeblockunderitaslongasaBooleanexpressionisTrueWaityouhavebeenkeepingupwiththeterminologyrightThatifwewritealineandenditwitha(colon)thenthattellsPythontostartanewblockofcodeThenweindentandthatrsquosthenewcodeThisisallaboutstructuringyourprogramssothatPythonknowswhatyoumeanIfyoudonotgetthatideathengobackanddosomemoreworkwithif-statementsfunctionsandthefor-loopuntilyougetitLateronwersquollhavesomeexercisesthatwilltrainyourbraintoreadthesestructuressimilartohowweburnedBooleanexpressionsintoyourbrainBacktowhile-loopsWhattheydoissimplydoatestlikeanif-statementbutinsteadofrunningthecodeblockoncetheyjumpbacktotheldquotoprdquowherethewhileisandrepeatAwhile-looprunsuntiltheexpressionisFalseHerersquostheproblemwithwhile-loopsSometimestheydonotstopThisisgreatifyourintentionistojustkeeploopinguntiltheendoftheuniverseOtherwiseyoualmostalwayswantyourloopstoendeventuallyToavoidtheseproblemstherearesomerulestofollow1Makesurethatyouusewhile-loopssparinglyUsuallyafor-loopisbetter

2ReviewyourwhilestatementsandmakesurethattheBooleantestwillbecomeFalseatsomepoint

3Whenindoubtprintoutyourtestvariableatthetopandbottomofthewhile-looptoseewhatitrsquosdoing

Inthisexerciseyoulearnthewhile-loopwhiledoingthesethreechecksClickheretoviewcodeimage

ex33py

1i=0

2numbers=[]

3

4whileilt6

5print(fAtthetopiisi)

6numbersappend(i)

7

8i=i+1

9print(Numbersnownumbers)

10print(fAtthebottomiisi)

11

12

13print(Thenumbers)

14

15fornuminnumbers

16print(num)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise33Session

$python36ex33py

Atthetopiis0

Numbersnow[0]

Atthebottomiis1

Atthetopiis1

Numbersnow[01]

Atthebottomiis2

Atthetopiis2

Numbersnow[012]

Atthebottomiis3

Atthetopiis3

Numbersnow[0123]

Atthebottomiis4

Atthetopiis4

Numbersnow[01234]

Atthebottomiis5

Atthetopiis5

Numbersnow[012345]

Atthebottomiis6

Thenumbers

0

1

2

3

4

5

StudyDrills

1Convertthiswhile-looptoafunctionthatyoucancallandreplace6inthetest(ilt6)withavariable

2Usethisfunctiontorewritethescripttotrydifferentnumbers3Addanothervariabletothefunctionargumentsthatyoucanpassinthatletsyouchangethe+1online8soyoucanchangehowmuchitincrementsby

4Rewritethescriptagaintousethisfunctiontoseewhateffectthathas5Writeittousefor-loopsandrangeDoyouneedtheincrementorinthemiddleanymoreWhathappensifyoudonotgetridofit

Ifatanytimeyouaredoingthisitgoescrazy(itprobablywill)justholddownCTRLandpressc(CTRL-c)andtheprogramwillabort

CommonStudentQuestionsWhatrsquosthedifferencebetweenafor-loopandawhile-loopAfor-loopcanonlyiterate(loop)ldquooverrdquocollectionsofthingsAwhile-loopcandoanykindofiteration(looping)youwantHoweverwhile-loopsarehardertogetrightandyounormallycangetmanythingsdonewithfor-loops

LoopsarehardHowdoIfigurethemoutThemainreasonpeopledonrsquotunderstandloopsisbecausetheycanrsquotfollowtheldquojumpingrdquothatthecodedoesWhenalooprunsitgoesthroughitsblockofcodeandattheenditjumpsbacktothetopTovisualizethisputprintstatementsallovertheloopprintingoutwhereintheloopPythonisrunningandwhatthevariablesaresettoatthosepointsWriteprintlinesbeforetheloopatthetopoftheloopinthemiddleandatthebottomStudytheoutputandtrytounderstandthejumpingthatrsquosgoingon

Exercise34AccessingElementsofLists

ListsareprettyusefulbutunlessyoucangetatthethingsinthemtheyarenrsquotallthatgoodYoucanalreadygothroughtheelementsofalistinorderbutwhatifyouwantsaythefifthelementYouneedtoknowhowtoaccesstheelementsofalistHerersquoshowyouwouldaccessthefirstelementofalistClickheretoviewcodeimage

animals=[beartigerpenguinzebra]

bear=animals[0]

Youtakealistofanimalsandthenyougetthefirst(1st)oneusing0HowdoesthatworkBecauseofthewaymathworksPythonstartsitslistsat0ratherthan1ItseemsweirdbuttherearemanyadvantagestothiseventhoughitismostlyarbitraryThebestwaytoexplainwhyisbyshowingyouthedifferencebetweenhowyouusenumbersandhowprogrammersusenumbersImagineyouarewatchingthefouranimalsinourlist([beartigerpenguinzebra])runinaraceTheycrossthefinishlineintheorderwehavetheminthislistTheracewasreallyexcitingbecausetheanimalsdidnrsquoteateachotherandsomehowmanagedtorunaraceYourfriendshowsuplateandwantstoknowwhowonDoesyourfriendsayldquoHeywhocameinzerothrdquoNohesaysldquoHeywhocameinfirstrdquoThisisbecausetheorderoftheanimalsisimportantYoucanrsquothavethesecondanimalwithoutthefirst(1st)animalandyoucanrsquothavethethirdwithoutthesecondItrsquosalsoimpossibletohavealdquozerothrdquoanimalsincezeromeansnothingHowcanyouhaveanothingwinaraceItjustdoesnrsquotmakesenseWecallthesekindsofnumbersldquoordinalrdquonumbersbecausetheyindicateanorderingofthingsProgrammershowevercanrsquotthinkthiswaybecausetheycanpickanyelementoutofalistatanypointToprogrammersthelistofanimalsismorelikeadeckofcardsIftheywantthetigertheygrabitIftheywantthezebratheycantakeittooThisneedtopullelementsoutoflistsatrandommeansthattheyneedawaytoindicateelementsconsistentlybyanaddressoranldquoindexrdquoandthebestwaytodothatistostarttheindicesat0TrustmeonthisthemathiswayeasierforthesekindsofaccessesThiskindofnumberisaldquocardinalrdquonumberandmeansyoucanpickatrandomsothereneedstobea0elementHowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourself

HowdoesthishelpyouworkwithlistsSimpleeverytimeyousaytoyourselfldquoIwantthethirdanimalrdquoyoutranslatethisldquoordinalrdquonumbertoaldquocardinalrdquonumberbysubtracting1Theldquothirdrdquoanimalisatindex2andisthepenguinYouhavetodothisbecauseyouhavespentyourwholelifeusingordinalnumbersandnowyouhavetothinkincardinalJustsubtract1andyoursquoregoodRememberordinal==ordered1stcardinal==cardsatrandom0LetrsquospracticethisTakethislistofanimalsandfollowtheexerciseswhereItellyoutowritedownwhatanimalyougetforthatordinalorcardinalnumberRememberifIsayldquofirstrdquoldquosecondrdquothenIrsquomusingordinalsosubtract1IfIgiveyoucardinal(likeldquoTheanimalat1rdquo)thenuseitdirectlyClickheretoviewcodeimage

animals=[bearpython36peacockkangaroowhale

platypus]

1Theanimalat12Thethird(3rd)animal3Thefirst(1st)animal4Theanimalat35Thefifth(5th)animal6Theanimalat27Thesixth(6th)animal8Theanimalat4

ForeachofthesewriteoutafullsentenceoftheformldquoThefirst(1st)animalisat0andisabearrdquoThensayitbackwardsldquoTheanimalat0isthe1stanimalandisabearrdquoUseyourPythontocheckyouranswers

StudyDrills1Withwhatyouknowofthedifferencebetweenthesetypesofnumberscanyouexplainwhytheyear2010inldquoJanuary12010rdquoreallyis2010andnot2009(Hintyoucanrsquotpickyearsatrandom)

2Writesomemorelistsandworkoutsimilarindexesuntilyoucantranslatethem

3UsePythontocheckyouranswers

Warning

ProgrammerswilltellyoutoreadthisguynamedDijkstraonthissubjectIrecommendyouavoidhiswritingsonthisunlessyouenjoybeingyelledatbysomeonewhostoppedprogrammingatthesametimeprogrammingstarted

Exercise35BranchesandFunctions

Youhavelearnedif-statementsfunctionsandlistsNowitrsquostimetobendyourmindTypethisinandseeifyoucanfigureoutwhatitrsquosdoingClickheretoviewcodeimage

ex35py

1fromsysimportexit

2

3defgold_room()

4print(ThisroomisfullofgoldHowmuchdoyoutake)

5

6choice=input(gt)

7if0inchoiceor1inchoice

8how_much=int(choice)

9else

10dead(Manlearntotypeanumber)

11

12ifhow_muchlt50

13print(Niceyourenotgreedyyouwin)

14exit(0)

15else

16dead(Yougreedybastard)

17

18

19defbear_room()

20print(Thereisabearhere)

21print(Thebearhasabunchofhoney)

22print(Thefatbearisinfrontofanotherdoor)

23print(Howareyougoingtomovethebear)

24bear_moved=False

25

26whileTrue

27choice=input(gt)

28

29ifchoice==takehoney

30dead(Thebearlooksatyouthenslapsyourface

off)

31elifchoice==tauntbearandnotbear_moved

32print(Thebearhasmovedfromthedoor)

33print(Youcangothroughitnow)

34bear_moved=True

35elifchoice==tauntbearandbear_moved

36dead(Thebeargetspissedoffandchewsyourleg

off)

37elifchoice==opendoorandbear_moved

38gold_room()

39else

40print(Igotnoideawhatthatmeans)

41

42

43defcthulhu_room()

44print(HereyouseethegreatevilCthulhu)

45print(Heitwhateverstaresatyouandyougoinsane)

46print(Doyoufleeforyourlifeoreatyourhead)

47

48choice=input(gt)

49

50iffleeinchoice

51start()

52elifheadinchoice

53dead(Wellthatwastasty)

54else

55cthulhu_room()

56

57

58defdead(why)

59print(whyGoodjob)

60exit(0)

61

62defstart()

63print(Youareinadarkroom)

64print(Thereisadoortoyourrightandleft)

65print(Whichonedoyoutake)

66

67choice=input(gt)

68

69ifchoice==left

70bear_room()

71elifchoice==right

72cthulhu_room()

73else

74dead(Youstumblearoundtheroomuntilyoustarve)

75

76

77start()

WhatYouShouldSeeHerersquosmeplayingthegameClickheretoviewcodeimage

Exercise35Session

$python36ex35py

Youareinadarkroom

Thereisadoortoyourrightandleft

Whichonedoyoutake

gtleft

Thereisabearhere

Thebearhasabunchofhoney

Thefatbearisinfrontofanotherdoor

Howareyougoingtomovethebear

gttauntbear

Thebearhasmovedfromthedoor

Youcangothroughitnow

gtopendoor

ThisroomisfullofgoldHowmuchdoyoutake

gt1000

YougreedybastardGoodjob

StudyDrills1Drawamapofthegameandhowyouflowthroughit2Fixallofyourmistakesincludingspellingmistakes3Writecommentsforthefunctionsyoudonotunderstand4AddmoretothegameWhatcanyoudotobothsimplifyandexpandit5Thegold_roomhasaweirdwayofgettingyoutotypeanumberWhatareallthebugsinthiswayofdoingitCanyoumakeitbetterthanwhatIrsquovewrittenLookathowint()worksforclues

CommonStudentQuestionsHelpHowdoesthisprogramworkWhenyougetstuckunderstandingapieceofcodesimplywriteanEnglishcommentaboveeverylineexplainingwhatthatlinedoesKeepyourcommentsshortandsimilartothecodeTheneitherdiagramhowthecodeworksorwriteaparagraphdescribingitIfyoudothatyoursquollgetit

WhydidyouwritewhileTrueThatmakesaninfiniteloopWhatdoesexit(0)doOnmanyoperatingsystemsaprogramcanabortwithexit(0)andthenumberpassedinwillindicateanerrorornotIfyoudoexit(1)thenitwillbeanerrorbutexit(0)willbeagoodexitThereasonitrsquosbackwardfromnormalBooleanlogic(with0==False)isthatyoucanusedifferentnumbersto

indicatedifferenterrorresultsYoucandoexit(100)foradifferenterrorresultthanexit(2)orexit(1)

Whyisinput()sometimeswrittenasinput(gt)Theparametertoinputisastringthatitshouldprintasapromptbeforegettingtheuserrsquosinput

Exercise36DesigningandDebugging

Nowthatyouknowif-statementsIrsquomgoingtogiveyousomerulesforfor-loopsandwhile-loopsthatwillkeepyououtoftroubleIrsquomalsogoingtogiveyousometipsondebuggingsothatyoucanfigureoutproblemswithyourprogramFinallyyouwilldesignalittlegamesimilartothelastexercisebutwithaslighttwist

Rulesforif-statements1Everyif-statementmusthaveanelse2IfthiselseshouldneverrunbecauseitdoesnrsquotmakesensethenyoumustuseadiefunctionintheelsethatprintsoutanerrormessageanddiesjustlikewedidinthelastexerciseThiswillfindmanyerrors

3Nevernestif-statementsmorethantwodeepandalwaystrytodothemonedeep

4Treatif-statementslikeparagraphswhereeachif-elif-elsegroupingislikeasetofsentencesPutblanklinesbeforeandafter

5YourBooleantestsshouldbesimpleIftheyarecomplexmovetheircalculationstovariablesearlierinyourfunctionanduseagoodnameforthevariable

IfyoufollowthesesimplerulesyouwillstartwritingbettercodethanmostprogrammersGobacktothelastexerciseandseeifIfollowedalloftheserulesIfnotfixmymistakes

WarningNeverbeaslavetotherulesinreallifeFortrainingpurposesyouneedtofollowtheserulestomakeyourmindstrongbutinreallifesometimestheserulesarejuststupidIfyouthinkaruleisstupidtrynotusingit

RulesforLoops1Useawhile-looponlytoloopforeverandthatmeansprobablyneverThisonlyappliestoPythonotherlanguagesaredifferent

2Useafor-loopforallotherkindsofloopingespeciallyifthereisa

fixedorlimitednumberofthingstoloopover

TipsforDebugging1DonotusealdquodebuggerrdquoAdebuggerislikedoingafull-bodyscanonasickpersonYoudonotgetanyspecificusefulinformationandyoufindawholelotofinformationthatdoesnrsquothelpandisjustconfusing

2Thebestwaytodebugaprogramistouseprinttoprintoutthevaluesofvariablesatpointsintheprogramtoseewheretheygowrong

3MakesurepartsofyourprogramsworkasyouworkonthemDonotwritemassivefilesofcodebeforeyoutrytorunthemCodealittlerunalittlefixalittle

HomeworkNowwriteagamesimilartotheonethatIcreatedinthelastexerciseItcanbeanykindofgameyouwantinthesameflavorSpendaweekonitmakingitasinterestingaspossibleForStudyDrillsuselistsfunctionsandmodules(rememberthosefromExercise13)asmuchaspossibleandfindasmanynewpiecesofPythonasyoucantomakethegameworkBeforeyoustartcodingyoumustdrawamapforyourgameCreatetheroomsmonstersandtrapsthattheplayermustgothroughonpaperbeforeyoucodeOnceyouhaveyourmaptrytocodeitupIfyoufindproblemswiththemapthenadjustitandmakethecodematchThebestwaytoworkonapieceofsoftwareisinsmallchunkslikethis

1OnasheetofpaperoranindexcardwritealistoftasksyouneedtocompletetofinishthesoftwareThisisyourto-dolist

2Picktheeasiestthingyoucandofromyourlist3WriteoutEnglishcommentsinyoursourcefileasaguideforhowyouwouldaccomplishthistaskinyourcode

4WritesomeofthecodeundertheEnglishcomments5Quicklyrunyourscriptsoseeifthatcodeworked6Keepworkinginacycleofwritingsomecoderunningittotestitandfixingituntilitworks

7CrossthistaskoffyourlistthenpickyournexteasiesttaskandrepeatThisprocesswillhelpyouworkonsoftwareinamethodicalandconsistentmannerAsyouworkupdateyourlistbyremovingtasksyoudonrsquotreallyneedandaddingonesyoudo

andaddingonesyoudo

Exercise37SymbolReview

ItrsquostimetoreviewthesymbolsandPythonwordsyouknowandpickupafewmoreforthenextfewlessonsIhavewrittenoutallthePythonsymbolsandkeywordsthatareimportanttoknowInthislessontakeeachkeywordandfirsttrytowriteoutwhatitdoesfrommemoryNextsearchonlineforitandseewhatitreallydoesThismaybedifficultbecausesomeofthesearedifficulttosearchforbuttryanywayIfyougetoneofthesewrongfrommemorymakeanindexcardwiththecorrectdefinitionandtrytoldquocorrectrdquoyourmemoryFinallyuseeachoftheseinasmallPythonprogramorasmanyasyoucangetdoneThegoalistofindoutwhatthesymboldoesmakesureyougotitrightcorrectitifyoudidnotthenuseittolockitin

Keywords

DataTypesFordatatypeswriteoutwhatmakesupeachoneForexamplewithstringswriteouthowyoucreateastringFornumberswriteoutafewnumbers

StringEscapeSequencesForstringescapesequencesusetheminstringstomakesuretheydowhatyouthinktheydo

OldStyleStringFormatsSamethingforstringformatsusetheminsomestringstoknowwhattheydoOlderPython2codeusestheseformattingcharacterstodowhatf-stringsdoTrythemoutasanalternative

OperatorsSomeofthesemaybeunfamiliartoyoubutlookthemupanywayFindoutwhattheydoandifyoustillcanrsquotfigureitoutsaveitforlater

SpendaboutaweekonthisbutifyoufinishfasterthatrsquosgreatThepointistotrytogetcoverageonallthesesymbolsandmakesuretheyarelockedinyourheadWhatrsquosalsoimportantistofindoutwhatyoudonotknowsoyoucanfixitlater

ReadingCodeNowfindsomePythoncodetoreadYoushouldbereadinganyPythoncodeyoucanandtryingtostealideasthatyoufindYouactuallyshouldhaveenoughknowledgetobeabletoreadbutmaybenotunderstandwhatthecodedoesWhatthislessonteachesishowtoapplythingsyouhavelearnedtounderstandotherpeoplersquoscodeFirstprintoutthecodeyouwanttounderstandYesprintitoutbecauseyoureyesandbrainaremoreusedtoreadingpaperthancomputerscreensMakesureyouprintafewpagesatatimeSecondgothroughyourprintoutandtakenotesonthefollowing

1Functionsandwhattheydo2Whereeachvariableisfirstgivenavalue3AnyvariableswiththesamenamesindifferentpartsoftheprogramThesemaybetroublelater

4Anyif-statementswithoutelseclausesAretheyright5Anywhile-loopsthatmightnotend6Anypartsofcodethatyoucanrsquotunderstandforwhateverreason

ThirdonceyouhaveallofthismarkeduptrytoexplainittoyourselfbywritingcommentsasyougoExplainthefunctionshowtheyareusedwhatvariablesareinvolvedandanythingyoucantofigurethiscodeoutLastonallofthedifficultpartstracethevaluesofeachvariablelinebylinefunctionbyfunctionInfactdoanotherprintoutandwriteinthemarginthevalueofeachvariablethatyouneedtoldquotracerdquoOnceyouhaveagoodideaofwhatthecodedoesgobacktothecomputerandreaditagaintoseeifyoufindnewthingsKeepfindingmorecodeanddoingthisuntilyoudonotneedtheprintoutsanymore

StudyDrills1Findoutwhataldquoflowchartrdquoisanddrawafew2Ifyoufinderrorsincodeyouarereadingtrytofixthemandsendtheauthoryourchanges

3AnothertechniqueforwhenyouarenotusingpaperistoputcommentswithyournotesinthecodeSometimesthesecouldbecometheactualcommentstohelpthenextperson

CommonStudentQuestionsHowwouldIsearchforthesethingsonlineSimplyputldquopython36rdquobeforeanythingyouwanttofindForexampletofindldquoyieldrdquosearchforldquopython36yieldrdquo

Exercise38DoingThingstoLists

YouhavelearnedaboutlistsWhenyoulearnedaboutwhile-loopsyouldquoappendedrdquonumberstotheendofalistandprintedthemoutTherewerealsoStudyDrillswhereyouweresupposedtofindalltheotherthingsyoucandotolistsinthePythondocumentationThatwasawhilebacksoreviewthosetopicsifyoudonotknowwhatIrsquomtalkingaboutFounditRememberitGoodWhenyoudidthisyouhadalistandyouldquocalledrdquothefunctionappendonitHoweveryoumaynotreallyunderstandwhatrsquosgoingonsoletrsquosseewhatwecandotolistsWhenyouwritemystuffappend(hello)youareactuallysettingoffachainofeventsinsidePythontocausesomethingtohappentothemystufflistHerersquoshowitworks1PythonseesyoumentionedmystuffandlooksupthatvariableItmighthavetolookbackwardtoseeifyoucreateditwith=ifitisafunctionargumentorifitrsquosaglobalvariableEitherwayithastofindmystufffirst

2Onceitfindsmystuffitreadsthe(period)operatorandstartstolookatvariablesthatareapartofmystuffSincemystuffisalistitknowsthatmystuffhasabunchoffunctions

3ItthenhitsappendandcomparesthenametoallthenamesthatmystuffsaysitownsIfappendisinthere(itis)thenPythongrabsthattouse

4NextPythonseesthe((openparenthesis)andrealizesldquoOhheythisshouldbeafunctionrdquoAtthispointitcalls(runsorexecutes)thefunctionjustlikenormalbutitcallsthefunctionwithanextraargument

5ThatextraargumentismystuffIknowweirdrightButthatrsquoshowPythonworkssoitrsquosbesttojustrememberitandassumethatrsquostheresultWhathappensattheendofallthisisafunctioncallthatlookslikeappend(mystuffhello)insteadofwhatyoureadwhichismystuffappend(hello)

ForthemostpartyoudonothavetoknowthatthisisgoingonbutithelpswhenyougeterrormessagesfromPythonlikethisClickheretoviewcodeimage

$python36

gtgtgtclassThing(object)

deftest(message)

print(message)

gtgtgta=Thing()

gtgtgtatest(hello)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

TypeErrortest()takesexactly1argument(2given)

gtgtgtWhatwasallthatWellthisismetypingintothePythonshell

andshowingyousomemagicYouhavenrsquotseenclassyetbutwersquollget

intothatlaterFornowyouseehowPythonsaidtest()takesexactly

1argument(2given)IfyouseethisitmeansthatPythonchanged

atest(hello)totest(ahello)andthatsomewheresomeonemessed

upanddidnrsquotaddtheargumentfora

ThismightbealottotakeinbutwersquoregoingtospendafewexercisesgettingthisconceptfirminyourbrainTokickthingsoffherersquosanexercisethatmixesstringsandlistsforallkindsoffunClickheretoviewcodeimage

ex38py

1ten_things=ApplesOrangesCrowsTelephoneLightSugar

2

3print(Waittherearenot10thingsinthatlistLetsfix

that)

4

5stuff=ten_thingssplit()

6more_stuff=[DayNightSongFrisbee

7CornBananaGirlBoy]

8

9whilelen(stuff)=10

10next_one=more_stuffpop()

11print(Addingnext_one)

12stuffappend(next_one)

13print(fTherearelen(stuff)itemsnow)

14

15print(Therewegostuff)

16

17print(Letsdosomethingswithstuff)

18

19print(stuff[1])

20print(stuff[-1])whoafancy

21print(stuffpop())

22print(join(stuff))whatcool

23print(join(stuff[35]))superstellar

WhatYouShouldSee

WhatYouShouldSeeClickheretoviewcodeimage

Waittherearenot10thingsinthatlistLetsfixthat

AddingBoy

Thereare7itemsnow

AddingGirl

Thereare8itemsnow

AddingBanana

Thereare9itemsnow

AddingCorn

Thereare10itemsnow

Therewego[ApplesOrangesCrowsTelephoneLight

SugarBoyGirlBananaCorn]

Letsdosomethingswithstuff

Oranges

Corn

Corn

ApplesOrangesCrowsTelephoneLightSugarBoyGirlBanana

TelephoneLight

WhatListsCanDoLetrsquossayyouwanttocreateacomputergamebasedonGoFishIfyoudonrsquotknowwhatGoFishistakethetimenowtogoreaduponitontheinternetTodothisyouwouldneedtohavesomewayoftakingtheconceptofaldquodeckofcardsrdquoandputtingitintoyourPythonprogramYouthenhavetowritePythoncodethatknowshowtoworkthisimaginaryversionofadeckofcardssothatapersonplayingyourgamethinksthatitrsquosrealevenifitisnrsquotWhatyouneedisaldquodeckofcardsrdquostructureandprogrammerscallthiskindofthingadatastructureWhatrsquosadatastructureIfyouthinkaboutitadatastructureisjustaformalwaytostructure(organize)somedata(facts)ItreallyisthatsimpleEventhoughsomedatastructurescangetinsanelycomplexalltheyareisjustawaytostorefactsinsideaprogramsoyoucanaccessthemindifferentwaysTheystructuredataIrsquollbegettingintothismoreinthenextexercisebutlistsareoneofthemostcommondatastructuresprogrammersuseAlistisanorderedlistofthingsyouwanttostoreandaccessrandomlyorlinearlybyanindexWhatRememberwhatIsaidthoughjustbecauseaprogrammersaidldquolistisalistrdquodoesnrsquotmeanthatitrsquosanymorecomplexthanwhatalistalreadyisintherealworldLetrsquoslookatthedeckofcardsasanexampleofalist1Youhaveabunchofcardswithvalues

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard

2Thosecardsareinastacklistorlistfromthetopcardtothebottomcard3Youcantakecardsoffthetopthebottomorthemiddleatrandom4Ifyouwanttofindaspecificcardyouhavetograbthedeckandgothroughitoneatatime

LetrsquoslookatwhatIsaidldquoAnorderedlistrdquoYesdeckofcardsisinorderwithafirstandalast

ldquoofthingsyouwanttostorerdquoYescardsarethingsIwanttostoreldquoandaccessrandomlyrdquoYesIcangrabacardfromanywhereinthedeck

ldquoorlinearlyrdquoYesifIwanttofindaspecificcardIcanstartatthebeginningandgoinorder

ldquobyanindexrdquoAlmostsincewithadeckofcardsifItoldyoutogetthecardatindex19yoursquodhavetocountuntilyoufoundthatoneInourPythonliststhecomputercanjustjumprighttoanyindexyougiveit

ThatisallalistdoesandthisshouldgiveyouawaytofigureoutconceptsinprogrammingEveryconceptinprogrammingusuallyhassomerelationshiptotherealworldAtleasttheusefulonesdoIfyoucanfigureoutwhattheanalogintherealworldisthenyoucanusethattofigureoutwhatthedatastructureshouldbeabletodo

WhentoUseListsYouusealistwheneveryouhavesomethingthatmatchesthelistdatastructurersquosusefulfeatures

1IfyouneedtomaintainorderRememberthisislistedordernotsortedorderListsdonotsortforyou

2IfyouneedtoaccessthecontentsrandomlybyanumberRememberthisisusingcardinalnumbersstartingat0

3Ifyouneedtogothroughthecontentslinearly(firsttolast)Rememberthatrsquoswhatfor-loopsarefor

Thisiswhenyouusealist

StudyDrills1TakeeachfunctionthatiscalledandgothroughthestepsforfunctioncallstotranslatethemtowhatPythondoesForexamplemore_stuffpop()ispop(more_stuff)

2TranslatethesetwowaystoviewthefunctioncallsinEnglishForexamplemore_stuffpop()readsasldquoCallpoponmore_stuffrdquoMeanwhilepop(more_stuff)meansldquoCallpopwithargumentmore_stuffrdquoUnderstandhowtheyarereallythesamething

3Goreadaboutobject-orientedprogrammingonlineConfusedIwastooDonotworryYouwilllearnenoughtobedangerousandyoucanslowlylearnmorelater

4ReaduponwhataclassisinPythonDonotreadabouthowotherlanguagesusethewordldquoclassrdquoThatwillonlymessyouup

5DonotworryIfyoudonothaveanyideawhatIrsquomtalkingaboutProgrammersliketofeelsmartsotheyinventedobject-orientedprogrammingnameditOOPandthenuseditwaytoomuchIfyouthinkthatrsquoshardyoushouldtrytouseldquofunctionalprogrammingrdquo

6Find10examplesofthingsintherealworldthatwouldfitinalistTrywritingsomescriptstoworkwiththem

CommonStudentQuestionsDidnrsquotyousaytonotusewhile-loopsYessojustremembersometimesyoucanbreaktherulesifyouhaveagoodreasonOnlyidiotsareslavestorulesallthetime

Whydoesjoin(stuff)notworkThewaythedocumentationforjoiniswrittendoesnrsquotmakesenseItdoesnotworklikethatandisinsteadamethodyoucallontheinsertedstringtoputbetweenthelisttobejoinedRewriteitlikejoin(stuff)

Whydidyouuseawhile-loopTryrewritingitwithafor-loopandseeifthatrsquoseasier

Whatdoesstuff[35]doThatextractsaldquoslicerdquofromthestufflistthatisfromelement3toelement4meaningitdoesnotincludeelement5Itrsquossimilartohowrange(35)wouldwork

Exercise39DictionariesOhLovelyDictionaries

YouarenowgoingtolearnabouttheDictionarydatastructureinPythonADictionary(ordict)isawaytostoredatajustlikealistbutinsteadofusingonlynumberstogetthedatayoucanusealmostanythingThisletsyoutreatadictlikeitrsquosadatabaseforstoringandorganizingdataLetrsquoscomparewhatdictscandotowhatlistscandoYouseealistletsyoudothisClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtthings=[abcd]

gtgtgtprint(things[1])

b

gtgtgtthings[1]=z

gtgtgtprint(things[1])

z

gtgtgtthings

[azcd]

YoucanusenumberstoindexintoalistmeaningyoucanusenumberstofindoutwhatrsquosinlistsYoushouldknowthisaboutlistsbynowbutmakesureyouunderstandthatyoucanonlyusenumberstogetitemsoutofalistAdictletsyouuseanythingnotjustnumbersYesadictassociatesonethingtoanothernomatterwhatitisTakealookClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtstuff=nameZedage39height612+2

gtgtgtprint(stuff[name])

Zed

gtgtgtprint(stuff[age])

39

gtgtgtprint(stuff[height])

74

gtgtgtstuff[city]=SF

gtgtgtprint(stuff[city])

SF

YouwillseethatinsteadofjustnumberswersquoreusingstringstosaywhatwewantfromthestuffdictionaryWecanalsoputnewthingsintothedictionary

withstringsItdoesnrsquothavetobestringsthoughWecanalsodothisExercise39PythonSession

gtgtgtstuff[1]=Wow

gtgtgtstuff[2]=Neato

gtgtgtprint(stuff[1])

Wow

gtgtgtprint(stuff[2])

NeatoInthiscodeIusednumbersandthenyoucanseethereare

numbersandstringsaskeysinthedictwhenIprintitIcoulduse

anythingWellalmostbutjustpretendyoucanuseanythingfornow

OfcourseadictionarythatyoucanonlyputthingsinisprettystupidsoherersquoshowyoudeletethingswiththedelkeywordClickheretoviewcodeimage

Exercise39PythonSession

gtgtgtdelstuff[city]

gtgtgtdelstuff[1]

gtgtgtdelstuff[2]

gtgtgtstuff

nameZedage39height74

ADictionaryExampleWersquollnowdoanexercisethatyoumuststudyverycarefullyIwantyoutotypethiscodeinandtrytounderstandwhatrsquosgoingonTakenoteofwhenyouputthingsinadictgetthemfromahashandalltheoperationsyouuseNoticehowthisexampleismappingstatestotheirabbreviationsandthentheabbreviationstocitiesinthestatesRemembermapping(orassociating)isthekeyconceptinadictionaryClickheretoviewcodeimage

ex39py

1createamappingofstatetoabbreviation

2states=

3OregonOR

4FloridaFL

5CaliforniaCA

6NewYorkNY

7MichiganMI

8

9

10createabasicsetofstatesandsomecitiesinthem

11cities=

12CASanFrancisco

13MIDetroit

14FLJacksonville

15

16

17addsomemorecities

18cities[NY]=NewYork

19cities[OR]=Portland

20

21printoutsomecities

22print(-10)

23print(NYStatehascities[NY])

24print(ORStatehascities[OR])

25

26printsomestates

27print(-10)

28print(Michigansabbreviationisstates[Michigan])

29print(Floridasabbreviationisstates[Florida])

30

31doitbyusingthestatethencitiesdict

32print(-10)

33print(Michiganhascities[states[Michigan]])

34print(Floridahascities[states[Florida]])

35

36printeverystateabbreviation

37print(-10)

38forstateabbrevinlist(statesitems())

39print(fstateisabbreviatedabbrev)

40

41printeverycityinstate

42print(-10)

43forabbrevcityinlist(citiesitems())

44print(fabbrevhasthecitycity)

45

46nowdobothatthesametime

47print(-10)

48forstateabbrevinlist(statesitems())

49print(fstatestateisabbreviatedabbrev)

50print(fandhascitycities[abbrev])

51

52print(-10)

53safelygetaabbreviationbystatethatmightnotbethere

54state=statesget(Texas)

55

56ifnotstate

57print(SorrynoTexas)

58

59getacitywithadefaultvalue

60city=citiesget(TXDoesNotExist)

61print(fThecityforthestateTXiscity)

WhatYouShouldSeeClickheretoviewcodeimage

Exercise39Session

$python36ex39py

----------

NYStatehasNewYork

ORStatehasPortland

----------

MichigansabbreviationisMI

FloridasabbreviationisFL

----------

MichiganhasDetroit

FloridahasJacksonville

----------

OregonisabbreviatedOR

FloridaisabbreviatedFL

CaliforniaisabbreviatedCA

NewYorkisabbreviatedNY

MichiganisabbreviatedMI

----------

CAhasthecitySanFrancisco

MIhasthecityDetroit

FLhasthecityJacksonville

NYhasthecityNewYork

ORhasthecityPortland

----------

OregonstateisabbreviatedOR

andhascityPortland

FloridastateisabbreviatedFL

andhascityJacksonville

CaliforniastateisabbreviatedCA

andhascitySanFrancisco

NewYorkstateisabbreviatedNY

andhascityNewYork

MichiganstateisabbreviatedMI

andhascityDetroit

----------

SorrynoTexas

ThecityforthestateTXisDoesNotExist

WhatDictionariesCanDo

WhatDictionariesCanDoAdictionaryisanotherexampleofadatastructureandlikealistitisoneofthemostcommonlyuseddatastructuresinprogrammingAdictionaryisusedtomaporassociatethingsyouwanttostoretokeysyouneedtogetthemAgainprogrammersdonrsquotuseatermlikeldquodictionaryrdquoforsomethingthatdoesnrsquotworklikeanactualdictionaryfullofwordssoletrsquosusethatasourrealworldexampleLetrsquossayyouwanttofindoutwhatthewordldquohonorificabilitudinitatibusrdquomeansTodayyouwouldsimplycopy-pastethatwordintoasearchengineandthenfindouttheanswerandwecouldsayasearchengineislikeareallyhugesupercomplexversionoftheOxfordEnglishDictionary(OED)Beforesearchengineswhatyouwoulddoisthis1GotoyourlibraryandgetldquothedictionaryrdquoLetrsquossayitrsquostheOED

2YouknowldquohonorificabilitudinitatibusrdquostartswiththeletterldquoHrdquosoyoulookonthesideofthebookforthelittletabthathasldquoHrdquoonit

3Skimthepagesuntilyouareclosetowhereldquohonrdquostarts4SkimafewmorepagesuntilyoufindldquohonorificabilitudinitatibusrdquoorhitthebeginningoftheldquohprdquowordsandrealizethiswordisnrsquotintheOED

5Onceyoufindtheentryyoureadthedefinitiontofigureoutwhatitmeans

ThisprocessisnearlyexactlythewayadictworksandyouarebasicallyldquomappingrdquothewordldquohonorificabilitudinitatibusrdquotoitsdefinitionAdictinPythonisjustlikeadictionaryintherealworldsuchastheOED

StudyDrills1Dothissamekindofmappingwithcitiesandstatesregionsinyourcountryorsomeothercountry

2FindthePythondocumentationfordictionariesandtrytodoevenmorethingstothem

3FindoutwhatyoucanrsquotdowithdictionariesAbigoneisthattheydonothaveordersotryplayingwiththat

CommonStudentQuestionsWhatisthedifferencebetweenalistandadictionaryAlistisforanorderedlistofitemsAdictionary(ordict)isformatchingsomeitems(calledldquokeysrdquo)tootheritems(calledldquovaluesrdquo)

WhatwouldIuseadictionaryforWhenyouhavetotakeonevalueandldquolookuprdquoanothervalueInfactyoucouldcalldictionariesldquolookuptablesrdquo

WhatwouldIusealistforUsealistforanysequenceofthingsthatneedstobeinorderandyouonlyneedtolookthemupbyanumericindex

WhatifIneedadictionarybutIneedittobeinorderTakealookatthecollectionsOrderedDictdatastructureinPythonSearchforitonlinetofindthedocumentation

Exercise40ModulesClassesandObjects

Pythoniscalledanldquoobject-orientedprogramminglanguagerdquoThismeansthereisaconstructinPythoncalledaclassthatletsyoustructureyoursoftwareinaparticularwayUsingclassesyoucanaddconsistencytoyourprogramssothattheycanbeusedinacleanerwayAtleastthatrsquosthetheoryIamnowgoingtoteachyouthebeginningsofobject-orientedprogrammingclassesandobjectsusingwhatyoualreadyknowaboutdictionariesandmodulesMyproblemisthatobject-orientedprogramming(OOP)isjustplainweirdYouhavetostrugglewiththistrytounderstandwhatIsayheretypeinthecodeandinthenextexerciseIrsquollhammeritinHerewego

ModulesAreLikeDictionariesYouknowhowadictionaryiscreatedandusedandthatitisawaytomaponethingtoanotherThatmeansifyouhaveadictionarywithakeyldquoapplerdquoandyouwanttogetitthenyoudothisClickheretoviewcodeimage

ex40apy

1mystuff=appleIAMAPPLES

2print(mystuff[apple])

KeepthisideaofldquogetXfromYrdquoinyourheadandnowthinkaboutmodulesYoursquovemadeafewsofarandyoushouldknowtheyare1APythonfilewithsomefunctionsorvariablesinit

2Whichyoucanimport3Andaccessthefunctionsorvariablesofwiththe(dot)operator

ImagineIhaveamodulethatIdecidetonamemystuffpyandIputafunctioninitcalledappleHerersquosthemodulemystuffpyClickheretoviewcodeimage

ex40apy

1thisgoesinmystuffpy

2defapple()

3print(IAMAPPLES)OnceIhavethiscodeIcanusethe

moduleMyStuffwithimportandthenaccesstheapplefunction

ex40apy

1importmystuff

2mystuffapple()Icouldalsoputavariableinitnamed

tangerineClickheretoviewcodeimage

ex40apy

1defapple()

2print(IAMAPPLES)

3

4thisisjustavariable

5tangerine=Livingreflectionofadream

Icanaccessthatthesamewayex40apy

1importmystuff

2

3mystuffapple()

4print(mystufftangerine)Referbacktothedictionaryandyou

shouldstarttoseehowthisissimilartousingadictionarybut

thesyntaxisdifferentLetrsquoscompareClickheretoviewcodeimage

ex40apy

1mystuff[apple]getapplefromdict

2mystuffapple()getapplefromthemodule

3mystufftangerinesamethingitsjustavariableThismeans

wehaveaverycommonpatterninPython1Takeakey=valuestyle

container

2GetsomethingoutofitbythekeyrsquosnameInthecaseofthedictionarythekeyisastringandthesyntaxis[key]InthecaseofthemodulethekeyisanidentifierandthesyntaxiskeyOtherthanthattheyarenearlythesamething

ClassesAreLikeModulesYoucanthinkaboutamoduleasaspecializeddictionarythatcanstorePythoncodesoyoucanaccessitwiththeoperatorPythonalsohasanotherconstructthatservesasimilarpurposecalledaclassAclassisawaytotakeagroupingof

functionsanddataandplacetheminsideacontainersoyoucanaccessthemwiththe(dot)operatorIfIweretocreateaclassjustlikethemystuffmoduleIrsquoddosomethinglikethisClickheretoviewcodeimage

ex40apy

1classMyStuff(object)

2

3def__init__(self)

4selftangerine=Andnowathousandyearsbetween

5

6defapple(self)

7print(IAMCLASSYAPPLES)Thatlookscomplicated

comparedtomodulesandthereisdefinitelyalotgoingonby

comparisonbutyoushouldbeabletomakeouthowthisislikea

ldquomini-modulerdquowithMyStuffhavinganapple()functioninitWhatis

probablyconfusingisthe__init__()functionanduseof

selftangerineforsettingthetangerineinstancevariable

HerersquoswhyclassesareusedinsteadofmodulesYoucantakethisMyStuffclassanduseittocraftmanyofthemmillionsatatimeifyouwantandeachonewonrsquotinterferewitheachotherWhenyouimportamodulethereisonlyonefortheentireprogramunlessyoudosomemonsterhacksBeforeyoucanunderstandthisthoughyouneedtoknowwhatanldquoobjectrdquoisandhowtoworkwithMyStuffjustlikeyoudowiththemystuffpymodule

ObjectsAreLikeImportIfaclassislikealdquomini-modulerdquothentherehastobeaconceptsimilartoimportbutforclassesThatconceptiscalledldquoinstantiaterdquowhichisjustafancyobnoxiousoverlysmartwaytosayldquocreaterdquoWhenyouinstantiateaclasswhatyougetiscalledanobjectYouinstantiate(create)aclassbycallingtheclasslikeitrsquosafunctionlikethisex40apy

1thing=MyStuff()

2thingapple()

3print(thingtangerine)Thefirstlineistheldquoinstantiaterdquo

operationanditrsquosalotlikecallingafunctionHoweverPython

coordinatesasequenceofeventsforyoubehindthescenesIrsquollgo

throughthesestepsusingtheprecedingcodeforMyStuff1Python

looksforMyStuff()andseesthatitisaclassyoursquovedefined

2Pythoncraftsanemptyobjectwithallthefunctionsyoursquovespecifiedintheclassusingdef

3Pythonthenlookstoseeifyoumadealdquomagicrdquo__init__functionandifyouhaveitcallsthatfunctiontoinitializeyournewlycreatedemptyobject

4IntheMyStufffunction__init__youthengetthisextravariableselfwhichisthatemptyobjectPythonmadeforyouandyoucansetvariablesonitjustlikeyouwouldwithamoduledictionaryorotherobject

5Inthiscaseyousetselftangerinetoasonglyricandthenyoursquoveinitializedthisobject

6NowPythoncantakethisnewlymintedobjectandassignittothethingvariableforyoutoworkwith

ThatrsquosthebasicsofhowPythondoesthisldquomini-importrdquowhenyoucallaclasslikeafunctionRememberthatthisisnotgivingyoutheclassbutinsteadisusingtheclassasablueprintforbuildingacopyofthattypeofthingKeepinmindthatIrsquomgivingyouaslightlyinaccurateideaofhowtheseworksothatyoucanstarttobuildupanunderstandingofclassesbasedonwhatyouknowaboutmodulesThetruthisclassesandobjectssuddenlydivergefrommodulesatthispointIfIwerebeingtotallyhonestIrsquodsaysomethingmorelikethisbullClassesarelikeblueprintsordefinitionsforcreatingnewmini-modules

bullInstantiationishowyoumakeoneofthesemini-modulesandimportitatthesametimeldquoInstantiaterdquojustmeanstocreateanobjectfromtheclass

bullTheresultingcreatedmini-moduleiscalledanobjectandyouthenassignittoavariabletoworkwithit

Atthispointobjectsbehavedifferentlyfrommodulesandthisshouldonlyserveasawayforyoutobridgeovertounderstandingclassesandobjects

GettingThingsfromThingsInowhavethreewaystogetthingsfromthingsClickheretoviewcodeimage

ex40apy

1dictstyle

2mystuff[apples]

3

4modulestyle

5mystuffapples()

6print(mystufftangerine)

7

8classstyle

9thing=MyStuff()

10thingapples()

11print(thingtangerine)

AFirstClassExampleYoushouldstartseeingthesimilaritiesinthesethreekey=valuecontainertypesandprobablyhaveabunchofquestionsHangonwiththequestionsasthenextexercisewillhammerhomeyourldquoobject-orientedvocabularyrdquoInthisexerciseIjustwantyoutotypeinthiscodeandgetitworkingsothatyouhavesomeexperiencebeforemovingonClickheretoviewcodeimage

ex40py

1classSong(object)

2

3def__init__(selflyrics)

4selflyrics=lyrics

5

6defsing_me_a_song(self)

7forlineinselflyrics

8print(line)

9

10happy_bday=Song([Happybirthdaytoyou

11Idontwanttogetsued

12SoIllstoprightthere])

13

14bulls_on_parade=Song([Theyrallyaroundthafamily

15Withpocketsfullofshells])

16

17happy_bdaysing_me_a_song()

18

19bulls_on_paradesing_me_a_song()

WhatYouShouldSee

Exercise40Session

$python36ex40py

Happybirthdaytoyou

Idontwanttogetsued

SoIllstoprightthere

Theyrallyaroundthafamily

Withpocketsfullofshells

StudyDrills1Writesomemoresongsusingthisandmakesureyouunderstandthatyoursquorepassingalistofstringsasthelyrics

2Putthelyricsinaseparatevariablethenpassthatvariabletotheclasstouseinstead

3SeeifyoucanhackonthisandmakeitdomorethingsDonrsquotworryifyouhavenoideahowjustgiveitatryandseewhathappensBreakittrashitthrashityoucanrsquothurtit

4Searchonlineforldquoobject-orientedprogrammingrdquoandtrytooverflowyourbrainwithwhatyoureadDonrsquotworryifitmakesabsolutelynosensetoyouHalfofthatstuffmakesnosensetometoo

CommonStudentQuestionsWhydoIneedselfwhenImake__init__orotherfunctionsforclassesIfyoudonrsquothaveselfthencodelikecheese=FrankisambiguousThatcodeisnrsquotclearaboutwhetheryoumeantheinstancersquoscheeseattributeoralocalvariablenamedcheeseWithselfcheese=Frankitrsquosveryclearyoumeantheinstanceattributeselfcheese

Exercise41LearningtoSpeakObject-Oriented

InthisexerciseIrsquomgoingtoteachyouhowtospeakldquoobject-orientedrdquoWhatIrsquolldoisgiveyouasmallsetofwordswithdefinitionsyouneedtoknowThenIrsquollgiveyouasetofsentenceswithholesinthemthatyoursquollhavetounderstandFinallyIrsquomgoingtogiveyoualargesetofexercisesthatyouhavetocompletetomakethesesentencessolidinyourvocabulary

WordDrillsclassTellPythontomakeanewtypeofthingobjectTwomeaningsthemostbasictypeofthingandanyinstanceofsomething

instanceWhatyougetwhenyoutellPythontocreateaclassdefHowyoudefineafunctioninsideaclassselfInsidethefunctionsinaclassselfisavariablefortheinstanceobjectbeingaccessed

inheritanceTheconceptthatoneclasscaninherittraitsfromanotherclassmuchlikeyouandyourparents

compositionTheconceptthataclasscanbecomposedofotherclassesaspartsmuchlikehowacarhaswheels

attributeApropertyclasseshavethatarefromcompositionandareusuallyvariables

is-aAphrasetosaythatsomethinginheritsfromanotherasinaldquosalmonrdquois-ardquofishldquo

has-aAphrasetosaythatsomethingiscomposedofotherthingsorhasatraitasinldquoasalmonhas-amouthrdquo

TakesometimetomakeflashcardsforthesetermsandmemorizethemAsusualthiswonrsquotmaketoomuchsenseuntilafteryouarefinishedwiththisexercisebutyouneedtoknowthebasewordsfirst

PhraseDrillsNextIhavealistofPythoncodesnippetsontheleftandtheEnglishsentencesforthem

classX(Y)ldquoMakeaclassnamedXthatis-aYrdquo

classX(object)def__init__(selfJ)ldquoclassXhas-a__init__thattakesselfandJparametersrdquo

classX(object)defM(selfJ)ldquoclassXhas-afunctionnamedMthattakesselfandJparametersrdquo

foo=X()ldquoSetfootoaninstanceofclassXrdquofooM(J)ldquoFromfoogettheMfunctionandcallitwithparametersselfJrdquo

fooK=QldquoFromfoogettheKattributeandsetittoQrdquoIneachofthesewhereyouseeXYMJKQandfooyoucantreatthoselikeblankspotsForexampleIcanalsowritethesesentencesasfollows1ldquoMakeaclassnamedthatis-aYrdquo

2ldquoclasshas-a__init__thattakesselfandparametersrdquo3ldquoclasshas-afunctionnamedthattakesselfandparametersrdquo4ldquoSettoaninstanceofclassrdquo5ldquoFromgetthefunctionandcallitwithself=andparametersrdquo

6ldquoFromgettheattributeandsetittordquoAgainwritetheseonsomeflashcardsanddrillthemPutthePythoncodesnippetonthefrontandthesentenceonthebackYouhavetobeabletosaythesentenceexactlythesameeverytimewheneveryouseethatformNotsortofthesamebutexactlythesame

CombinedDrillsThefinalpreparationforyouistocombinethewordsdrillswiththephrasedrillsWhatIwantyoutodoforthisdrillisthis

1Takeaphrasecardanddrillit2Flipitoverandreadthesentenceandforeachwordinthesentencethatisinyourwordsdrillsgetthatcard

3Drillthosewordsforthatsentence4Keepgoinguntilyouareboredthentakeabreakanddoitagain

AReadingTestInowhavealittlePythonhackscriptthatwilldrillyouonthesewordsyouknowinaninfinitemannerThisisasimplescriptyoushouldbeabletofigureoutandtheonlythingitdoesisusealibrarycalledurllibtodownloadalist

ofwordsIhaveHerersquosthescriptwhichyoushouldenterintooop_testpytoworkwithitClickheretoviewcodeimage

ex41py

1importrandom

2fromurllibrequestimporturlopen

3importsys

4

5WORD_URL=httplearncodethehardwayorgwordstxt

6WORDS=[]

7

8PHRASES=

9class()

10Makeaclassnamedthatis-a

11class(object)ntdef__init__(self)

12classhas-a__init__thattakesselfand

params

13class(object)ntdef(self)

14classhas-afunctionthattakesselfand

params

15=()

16Settoaninstanceofclass

17()

18Fromgetthefunctioncallitwithparamsself

19=

20Fromgettheattributeandsetitto

21

22

23dotheywanttodrillphrasesfirst

24iflen(sysargv)==2andsysargv[1]==english

25PHRASE_FIRST=True

26else

27PHRASE_FIRST=False

28

29loadupthewordsfromthewebsite

30forwordinurlopen(WORD_URL)readlines()

31WORDSappend(str(wordstrip()encoding=utf-8))

32

33

34defconvert(snippetphrase)

35class_names=[wcapitalize()forwin

36randomsample(WORDSsnippetcount())]

37other_names=randomsample(WORDSsnippetcount())

38results=[]

39param_names=[]

40

41foriinrange(0snippetcount())

42param_count=randomrandint(13)

43param_namesappend(join(

44randomsample(WORDSparam_count)))

45

46forsentenceinsnippetphrase

47result=sentence[]

48

49fakeclassnames

50forwordinclass_names

51result=resultreplace(word1)

52

53fakeothernames

54forwordinother_names

55result=resultreplace(word1)

56

57fakeparameterlists

58forwordinparam_names

59result=resultreplace(word1)

60

61resultsappend(result)

62

63returnresults

64

65

66keepgoinguntiltheyhitCTRL-D

67try

68whileTrue

69snippets=list(PHRASESkeys())

70randomshuffle(snippets)

71

72forsnippetinsnippets

73phrase=PHRASES[snippet]

74questionanswer=convert(snippetphrase)

75ifPHRASE_FIRST

76questionanswer=answerquestion

77

78print(question)

79

80input(lt)

81print(fANSWERanswernn)

82exceptEOFError

83print(nBye)Runthisscriptandtrytotranslatethe

ldquoobject-orientedphrasesrdquointoEnglishtranslationsYoushouldsee

thatthePHRASESdicthasbothformsandthatyoujusthavetoenter

thecorrectone

PracticeEnglishtoCode

PracticeEnglishtoCodeNextyoushouldrunthescriptwiththeldquoenglishrdquooptionsothatyoudrilltheinverseoperation

$pythonoop_testpyenglishRememberthatthesephrasesareusing

nonsensewordsPartoflearningtoreadcodewellistostopplacing

somuchmeaningonthenamesusedforvariablesandclassesToo

oftenpeoplewillreadawordlikeldquoCorkrdquoandsuddenlygetderailed

becausethatwordwillconfusethemaboutthemeaningIntheabove

exampleldquoCorkrdquoisjustanarbitrarynamechosenforaclassDonrsquot

placeanyothermeaningonitandinsteadtreatitlikethepatterns

Irsquovegivenyou

ReadingMoreCodeYouarenowtogoonanewquesttoreadevenmorecodetoreadthephrasesyoujustlearnedinthecodeyoureadYouwilllookforallthefileswithclassesandthendothefollowing

1Foreachclassgiveitsnameandwhatotherclassesitinheritsfrom2Underthatlisteveryfunctionithasandtheparameterstheytake3Listalloftheattributesitusesonitsself4Foreachattributegivetheclassthisattributeis

ThegoalistogothroughrealcodeandstartlearningtoldquopatternmatchrdquothephrasesyoujustlearnedagainsthowtheyrsquoreusedIfyoudrillthisenoughyoushouldstarttoseethesepatternsshoutatyouinthecodewhereasbeforetheyjustseemedlikevagueblankspotsyoudidnrsquotknow

CommonStudentQuestionsWhatdoesresult=sentence[]doThatrsquosaPythonwayofcopyingalistYoursquoreusingthelistslicesyntax[]toeffectivelymakeaslicefromtheveryfirstelementtotheverylastone

ThisscriptishardtogetrunningBythispointyoushouldbeabletotypethisinandgetitworkingItdoeshaveafewlittletrickshereandtherebuttherersquosnothingcomplexaboutitJustdoallthethingsyoursquovelearnedsofartodebugscriptsTypeeachlineinconfirmthatitrsquosexactlylikemineandresearchanythingyoudonrsquotknowonline

ItrsquosstilltoohardYoucandothisTakeitveryslowcharacterbycharacterifyouhavetobuttypeitinexactlyandfigureoutwhatitdoes

Exercise42Is-AHas-AObjectsandClasses

AnimportantconceptthatyouhavetounderstandisthedifferencebetweenaclassandanobjectTheproblemisthereisnorealldquodifferencerdquobetweenaclassandanobjectTheyareactuallythesamethingatdifferentpointsintimeIwilldemonstratewithaZenkoanWhatisthedifferencebetweenafishandasalmonDidthatquestionsortofconfuseyouReallysitdownandthinkaboutitforaminuteImeanafishandasalmonaredifferentbutwaittheyarethesamethingrightAsalmonisakindoffishsoImeanitrsquosnotdifferentButatthesametimeasalmonisaparticulartypeoffishsoitrsquosactuallydifferentfromallotherfishThatrsquoswhatmakesitasalmonandnotahalibutSoasalmonandafisharethesamebutdifferentWeirdThisquestionisconfusingbecausemostpeopledonotthinkaboutrealthingsthiswaybuttheyintuitivelyunderstandthemYoudonotneedtothinkaboutthedifferencebetweenafishandasalmonbecauseyouknowhowtheyarerelatedYouknowasalmonisakindoffishandthatthereareotherkindsoffishwithouthavingtounderstandthatLetrsquostakeitonestepfurtherLetrsquossayyouhaveabucketfullofthreesalmonandbecauseyouareanicepersonyouhavedecidedtonamethemFrankJoeandMaryNowthinkaboutthisquestionWhatisthedifferencebetweenMaryandasalmonAgainthisisaweirdquestionbutitrsquosabiteasierthanthefishversussalmonquestionYouknowthatMaryisasalmonsoshersquosnotreallydifferentShersquosjustaspecificldquoinstancerdquoofasalmonJoeandFrankarealsoinstancesofsalmonWhatdoImeanwhenIsayinstanceImeantheywerecreatedfromsomeothersalmonandnowrepresentarealthingthathassalmon-likeattributesNowforthemind-bendingideaFishisaclassandSalmonisaclassandMaryisanobjectThinkaboutthatforasecondLetrsquosbreakitdownslowlyandseeifyougetitAfishisaclassmeaningitrsquosnotarealthingbutratherawordweattachtoinstancesofthingswithsimilarattributesGotfinsGotgillsLivesinwaterAlrightitrsquosprobablyafishSomeonewithaPhDthencomesalongandsaysldquoNomyyoungfriendthisfishisactuallySalmosalaraffectionatelyknownasasalmonrdquoThisprofessorhasjustclarifiedthefishfurtherandmadeanewclasscalledldquoSalmonrdquothathas

morespecificattributesLongernosereddishfleshbiglivesintheoceanorfreshwatertastyProbablyasalmonFinallyacookcomesalongandtellsthePhDldquoNoyouseethisSalmonrighthereIrsquollcallherMaryandIrsquomgoingtomakeatastyfilletoutofherwithanicesaucerdquoNowyouhavethisinstanceofasalmon(whichalsoisaninstanceofafish)namedMaryturnedintosomethingrealthatisfillingyourbellyIthasbecomeanobjectThereyouhaveitMaryisakindofsalmonthatisakindoffishmdashobjectisaclassisaclass

HowThisLooksinCodeThisisaweirdconceptbuttobeveryhonestyouonlyhavetoworryaboutitwhenyoumakenewclassesandwhenyouuseaclassIwillshowyoutwotrickstohelpyoufigureoutwhethersomethingisaclassoranobjectFirstyouneedtolearntwocatchphrasesldquois-ardquoandldquohas-ardquoYouusethephraseis-awhenyoutalkaboutobjectsandclassesbeingrelatedtoeachotherbyaclassrelationshipYouusehas-awhenyoutalkaboutobjectsandclassesthatarerelatedonlybecausetheyreferenceeachotherNowgothroughthispieceofcodeandreplaceeachcommentwithacommentthatsayswhetherthenextlinerepresentsanis-aorahas-arelationshipandwhatthatrelationshipisInthebeginningofthecodeIrsquovelaidoutafewexamplessoyoujusthavetowritetheremainingonesRememberis-aistherelationshipbetweenfishandsalmonwhilehas-aistherelationshipbetweensalmonandgillsClickheretoviewcodeimage

ex42py

1Animalis-aobject(yessortofconfusing)lookatthe

extracredit

2classAnimal(object)

3pass

4

5

6classDog(Animal)

7

8def__init__(selfname)

9

10selfname=name

11

12

13classCat(Animal)

14

15def__init__(selfname)

16

17selfname=name

18

19

20classPerson(object)

21

22def__init__(selfname)

23

24selfname=name

25

26Personhas-apetofsomekind

27selfpet=None

28

29

30classEmployee(Person)

31

32def__init__(selfnamesalary)

33hmmwhatisthisstrangemagic

34super(Employeeself)__init__(name)

35

36selfsalary=salary

37

38

39classFish(object)

40pass

41

42

43classSalmon(Fish)

44pass

45

46

47classHalibut(Fish)

48pass

49

50

51roveris-aDog

52rover=Dog(Rover)

53

54

55satan=Cat(Satan)

56

57

58mary=Person(Mary)

59

60

61marypet=satan

62

63

64frank=Employee(Frank120000)

65

66

67frankpet=rover

68

69

70flipper=Fish()

71

72

73crouse=Salmon()

74

75

76harry=Halibut()

AboutclassName(object)InPython3youdonotneedtoaddthe(object)afterthenameoftheclassbutthePythoncommunitybelievesinldquoexplicitisbetterthanimplicitrdquosoIandotherPythonexpertshavedecidedtoincludeitYoumayrunintocodethatdoesnothave(object)aftersimpleclassesandthoseclassesareperfectlyfineandwillworkwithclassesyoucreatethatdohave(object)AtthispointitissimplyextradocumentationandhasnoimpactonhowyourclassesworkInPython2therewasadifferencebetweenthetwotypesofclassesbutnowyoudonrsquothavetoworryaboutitTheonlytrickyparttousing(object)involvesthementalgymnasticsofsayingldquoclassNameisaclassoftypeobjectrdquoThatmaysoundconfusingtoyounowsinceitrsquosaclassthatrsquosanameobjectthatrsquosaclassbutdonrsquotfeelbadaboutthatJustthinkofclassName(object)assayingldquothisisabasicsimpleclassrdquoandyoursquollbefineFinallyinthefuturethestylesandtastesofPythonprogrammersmaychangeandthisexplicituseof(object)mightbeseenasasignthatyouareabadprogrammerIfthathappenssimplystopusingitortellthemldquoPythonZensaysexplicitisbetterthanimplicitrdquo

StudyDrills1ResearchwhyPythonaddedthisstrangeobjectclassandwhatthatmeans2Isitpossibletouseaclasslikeitrsquosanobject3FillouttheanimalsfishandpeopleinthisexercisewithfunctionsthatmakethemdothingsSeewhathappenswhenfunctionsareinaldquobase

classrdquolikeAnimalversusinsayDog4Findotherpeoplersquoscodeandworkoutalltheis-aandhas-arelationships5Makesomenewrelationshipsthatarelistsanddictionariessoyoucanalsohaveldquohas-manyrdquorelationships

6Doyouthinktherersquossuchthingasanldquois-manyrdquorelationshipReadaboutldquomultipleinheritancerdquothenavoiditifyoucan

CommonStudentQuestionsWhatarethesecommentsforThoseareldquofill-in-the-blankrdquocommentsthatyouaresupposedtofillinwiththerightis-aandhas-aconceptsReadthisexerciseagainandlookattheothercommentstoseewhatImean

Whatisthepointofselfpet=NoneThatmakessurethattheselfpetattributeofthatclassissettoadefaultofNone

Whatdoessuper(Employeeself)__init__(name)doThatrsquoshowyoucanrunthe__init__methodofaparentclassreliablySearchforldquopython36superrdquoandreadthevariousadviceonitbeingevilandgoodforyou

Exercise43BasicObject-OrientedAnalysisandDesign

IrsquomgoingtodescribeaprocesstousewhenyouwanttobuildsomethingusingPythonspecificallywithobject-orientedprogramming(OOP)WhatImeanbyaldquoprocessrdquoisthatIrsquollgiveyouasetofstepsthatyoudoinorderbutthatyouarenrsquotmeanttobeaslavetoandthatmightnotalwaysworkforeveryproblemTheyarejustagoodstartingpointformanyprogrammingproblemsandshouldnrsquotbeconsideredtheonlywaytosolvethesetypesofproblemsThisprocessisjustonewaytodoitthatyoucanfollowTheprocessisasfollows1Writeordrawabouttheproblem

2Extractkeyconceptsfrom1andresearchthem3Createaclasshierarchyandobjectmapfortheconcepts4Codetheclassesandatesttorunthem5Repeatandrefine

ThewaytolookatthisprocessisthatitisldquotopdownrdquomeaningitstartsfromtheveryabstractlooseideaandthenslowlyrefinesituntiltheideaissolidandsomethingyoucancodeIstartbyjustwritingabouttheproblemandtryingtothinkupanythingIcanaboutitMaybeIrsquollevendrawadiagramortwomaybeamapofsomekindorevenwritemyselfaseriesofemailsdescribingtheproblemThisgivesmeawaytoexpressthekeyconceptsintheproblemandalsoexplorewhatImightalreadyknowaboutitThenIgothroughthesenotesdrawingsanddescriptionsandIpulloutthekeyconceptsTherersquosasimpletricktodoingthisImakealistofallthenounsandverbsinmywritinganddrawingsthenwriteouthowtheyrsquorerelatedThisgivesmeagoodlistofnamesforclassesobjectsandfunctionsinthenextstepItakethislistofconceptsandthenresearchanythatIdonrsquotunderstandsoIcanrefinethemfurtherifneededOnceIhavemylistofconceptsIcreateasimpleoutlinetreeoftheconceptsandhowtheyarerelatedasclassesIcanusuallytakemylistofnounsandstartaskingldquoIsthisonelikeotherconceptnounsThatmeanstheyhaveacommonparentclasssowhatisitcalledrdquoIkeepdoingthisuntilIhaveaclasshierarchythatrsquosjustasimpletreelistoradiagramThenItaketheverbsIhaveandseeifthosearefunctionnamesforeachclassandputtheminmytree

WiththisclasshierarchyfiguredoutIsitdownandwritesomebasicskeletoncodethathasjusttheclassestheirfunctionsandnothingmoreIthenwriteatestthatrunsthiscodeandmakessuretheclassesIrsquovemademakesenseandworkrightSometimesImaywritethetestfirstandothertimesImightwritealittletestalittlecodealittletestandsoonuntilIhavethewholethingbuiltFinallyIkeepcyclingoverthisprocessrepeatingitandrefiningasIgoandmakingitasclearasIcanbeforedoingmoreimplementationIfIgetstuckatanyparticularpartbecauseofaconceptorproblemIhavenrsquotanticipatedthenIsitdownandstarttheprocessoveronjustthatparttofigureitoutmorebeforecontinuingIwillnowgothroughthisprocesswhilecomingupwithagameengineandagameforthisexercise

TheAnalysisofaSimpleGameEngineThegameIwanttomakeiscalledldquoGothonsfromPlanetPercal25rdquoanditwillbeasmallspaceadventuregameWithnothingmorethanthatconceptinmymindIcanexploretheideaandfigureouthowtomakethegamecometolife

WriteorDrawAbouttheProblemIrsquomgoingtowritealittleparagraphforthegameldquoAlienshaveinvadedaspaceshipandourherohastogothroughamazeofroomsdefeatingthemsohecanescapeintoanescapepodtotheplanetbelowThegamewillbemorelikeaZorkorAdventuretypegamewithtextoutputsandfunnywaystodieThegamewillinvolveanenginethatrunsamapfullofroomsorscenesEachroomwillprintitsowndescriptionwhentheplayerentersitandthentelltheenginewhatroomtorunnextoutofthemaprdquoAtthispointIhaveagoodideaforthegameandhowitwouldrunsonowIwanttodescribeeachsceneDeathThisiswhentheplayerdiesandshouldbesomethingfunny

CentralCorridorThisisthestartingpointandhasaGothonalreadystandingtherethattheplayershavetodefeatwithajokebeforecontinuing

LaserWeaponArmoryThisiswheretheherogetsaneutronbombtoblowuptheshipbeforegettingtotheescapepodIthasakeypadtheherohastoguessthenumberfor

TheBridgeThisisanotherbattlescenewithaGothonwheretheheroplacesthebomb

EscapePodThisiswheretheheroescapesbutonlyafterguessingtherightescapepod

AtthispointImightdrawoutamapofthesemaybewritemoredescriptionsofeachroommdashwhatevercomestomindasIexploretheproblem

ExtractKeyConceptsandResearchThemInowhaveenoughinformationtoextractsomeofthenounsandanalyzetheirclasshierarchyFirstImakealistofallthenouns

bullAlienbullPlayerbullShipbullMazebullRoombullScenebullGothonbullEscapePodbullPlanetbullMapbullEnginebullDeathbullCentralCorridorbullLaserWeaponArmorybullTheBridge

IwouldalsopossiblygothroughalltheverbsandseeifanyofthemmightbegoodfunctionnamesbutIrsquollskipthatfornowAtthispointImightalsoresearcheachoftheseconceptsandanythingIdonrsquotknowrightnowForexampleImightplayafewofthesetypesofgamesandmakesureIknowhowtheyworkImightresearchhowshipsaredesignedorhowbombsworkMaybeIrsquollresearchsometechnicalissuelikehowtostorethegamersquosstateinadatabaseAfterIrsquovedonethisresearchImightstartoveratstep1basedonnewinformationIhaveandrewritemydescriptionandextractnewconcepts

CreateaClassHierarchyandObjectMapfortheConceptsOnceIhavethatIturnitintoaclasshierarchybyaskingldquoWhatissimilartootherthingsrdquoIalsoaskldquoWhatisbasicallyjustanotherwordforanotherthingrdquo

RightawayIseethatldquoRoomrdquoandldquoScenerdquoarebasicallythesamethingdependingonhowIwanttodothingsIrsquomgoingtopickldquoScenerdquoforthisgameThenIseethatallthespecificroomslikeldquoCentralCorridorrdquoarebasicallyjustScenesIseealsothatDeathisbasicallyaScenewhichconfirmsmychoiceofldquoScenerdquooverldquoRoomrdquosinceyoucanhaveadeathscenebutadeathroomiskindofoddldquoMazerdquoandldquoMaprdquoarebasicallythesamesoIrsquomgoingtogowithldquoMaprdquosinceIuseditmoreoftenIdonrsquotwanttodoabattlesystemsoIrsquomgoingtoignoreldquoAlienrdquoandldquoPlayerrdquoandsavethatforlaterTheldquoPlanetrdquocouldalsojustbeanothersceneinsteadofsomethingspecificAfterallofthatthoughtprocessIstarttomakeaclasshierarchythatlookslikethisinmytexteditorMapEngineSceneDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodIthengothroughandfigureoutwhatactionsareneededoneachthingbasedonverbsinthedescriptionForexampleIknowfromthedescriptionIrsquomgoingtoneedawaytoldquorunrdquotheengineldquogetthenextscenerdquofromthemapgettheldquoopeningscenerdquoandldquoenterrdquoasceneIrsquolladdthoselikethisMapndashnext_scenendashopening_sceneEnginendashplayScenendashenterDeathCentralCorridorLaserWeaponArmoryTheBridgeEscapePodNoticehowIjustput-enterunderScenesinceIknowthatallthescenesunderitwillinherititandhavetooverrideitlater

CodetheClassesandaTesttoRunThemOnceIhavethistreeofclassesandsomeofthefunctionsIopenupasourcefileinmyeditorandtrytowritethecodeforitUsuallyIrsquolljustcopy-pastethetreeintothesourcefileandthenedititintoclassesHerersquosasmallexampleofhow

intothesourcefileandthenedititintoclassesHerersquosasmallexampleofhowthismightlookatfirstwithasimplelittletestattheendofthefileClickheretoviewcodeimage

ex43_classespy

1classScene(object)

2

3defenter(self)

4pass

5

6

7classEngine(object)

8

9def__init__(selfscene_map)

10pass

11

12defplay(self)

13pass

14

15classDeath(Scene)

16

17defenter(self)

18pass

19

20classCentralCorridor(Scene)

21

22defenter(self)

23pass

24

25classLaserWeaponArmory(Scene)

26

27defenter(self)

28pass

29

30classTheBridge(Scene)

31

32defenter(self)

33pass

34

35classEscapePod(Scene)

36

37defenter(self)

38pass

39

40

41classMap(object)

42

43def__init__(selfstart_scene)

44pass

45

46defnext_scene(selfscene_name)

47pass

48

49defopening_scene(self)

50pass

51

52

53a_map=Map(central_corridor)

54a_game=Engine(a_map)

55a_gameplay()InthisfileyoucanseethatIsimplyreplicated

thehierarchyIwantedandthenaddedalittlebitofcodeattheend

torunitandseeifitallworksinthisbasicstructureInthe

latersectionsofthisexerciseyoursquollfillintherestofthiscode

andmakeitworktomatchthedescriptionofthegame

RepeatandRefineThelaststepinmylittleprocessisnrsquotsomuchastepasitisawhile-loopYoudonrsquoteverdothisasaone-passoperationInsteadyougobackoverthewholeprocessagainandrefineitbasedoninformationyoursquovelearnedfromlaterstepsSometimesIrsquollgettostep3andrealizethatIneedtoworkon1and2moresoIrsquollstopandgobackandworkonthoseSometimesIrsquollgetaflashofinspirationandjumptotheendtocodeupthesolutioninmyheadwhileIhaveittherebutthenIrsquollgobackanddothepreviousstepstomakesureIcoverallthepossibilitiesIhaveTheotherideainthisprocessisthatitrsquosnotjustsomethingyoudoatonesinglelevelbutsomethingthatyoucandoateverylevelwhenyourunintoaparticularproblemLetrsquossayIdonrsquotknowhowtowritetheEngineplaymethodyetIcanstopanddothiswholeprocessonjustthatonefunctiontofigureouthowtowriteit

TopDownversusBottomUpTheprocessistypicallylabeledldquotopdownrdquosinceitstartsatthemostabstractconcepts(thetop)andworksitswaydowntoactualimplementationIwantyoutousethisprocessIjustdescribedwhenanalyzingproblemsinthebookfromnowonbutyoushouldknowthattherersquosanotherwaytosolveproblemsinprogrammingthatstartswithcodeandgoesldquouprdquototheabstractconceptsThisotherwayislabeledldquobottomuprdquoHerearethegeneralstepsyoufollowtodothis

1Takeasmallpieceoftheproblemhackonsomecodeandgetittorunbarely

barely2Refinethecodeintosomethingmoreformalwithclassesandautomatedtests

3Extractthekeyconceptsyoursquoreusingandresearchthem4Writeadescriptionofwhatrsquosreallygoingon5Gobackandrefinethecodepossiblythrowingitoutandstartingover6Repeatmovingontosomeotherpieceoftheproblem

IfindthisprocessisbetteronceyoursquoremoresolidatprogrammingandarenaturallythinkingincodeaboutproblemsThisprocessisverygoodwhenyouknowsmallpiecesoftheoverallpuzzlebutmaybedonrsquothaveenoughinformationyetabouttheoverallconceptBreakingitdowninlittlepiecesandexploringwithcodethenhelpsyouslowlygrindawayattheproblemuntilyoursquovesolveditHoweverrememberthatyoursolutionwillprobablybemeanderingandweirdsothatrsquoswhymyversionofthisprocessinvolvesgoingbackandfindingresearchthencleaningthingsupbasedonwhatyoursquovelearned

TheCodeforldquoGothonsfromPlanetPercal25rdquoStopIrsquomgoingtoshowyoumyfinalsolutiontotheprecedingproblembutIdonrsquotwantyoutojustjumpinandtypethisupIwantyoutotaketheroughskeletoncodeIdidandtrytomakeitworkbasedonthedescriptionOnceyouhaveyoursolutionthenyoucancomebackandseehowIdiditIrsquomgoingtobreakthisfinalfileex43pydownintosectionsandexplaineachoneratherthandumpallthecodeatonceClickheretoviewcodeimage

ex43py

1fromsysimportexit

2fromrandomimportrandint

3fromtextwrapimportdedentThisisjustourbasicimportsfor

thegameTheonlynewthingistheimportofthededentfunction

fromthetextwrapmoduleThislittlefunctionwillhelpuswriteour

roomdescriptionsusing(triple-quote)stringsItsimplystrips

leadingwhite-spacefromthebeginningsoflinesinastringWithout

thisfunctionusingstylestringsfailsbecausetheyare

indentedonthescreenthesamelevelasinthePythoncode

Clickheretoviewcodeimage

ex43py

1classScene(object)

2

3defenter(self)

4print(Thissceneisnotyetconfigured)

5print(Subclassitandimplemententer())

6exit(1)AsyousawintheskeletoncodeIhaveabase

classforScenethatwillhavethecommonthingsthatallscenesdo

Inthissimpleprogramtheydonrsquotdomuchsothisismorea

demonstrationofwhatyouwoulddotomakeabaseclass

Clickheretoviewcodeimage

ex43py

1classEngine(object)

2

3def__init__(selfscene_map)

4selfscene_map=scene_map

5

6defplay(self)

7current_scene=selfscene_mapopening_scene()

8last_scene=selfscene_mapnext_scene(finished)

9

10whilecurrent_scene=last_scene

11next_scene_name=current_sceneenter()

12current_scene=

selfscene_mapnext_scene(next_scene_name)

13

14besuretoprintoutthelastscene

15current_sceneenter()IalsohavemyEngineclassand

youcanseehowIrsquomalreadyusingthemethodsforMapopening_scene

andMapnext_sceneBecauseIrsquovedoneabitofplanningIcanjust

assumeIrsquollwritethoseandthenusethembeforeIrsquovewrittentheMap

class

Clickheretoviewcodeimage

ex43py

1classDeath(Scene)

2

3quips=[

4YoudiedYoukindasuckatthis

5YourMomwouldbeproudifsheweresmarter

6Suchaluser

7Ihaveasmallpuppythatsbetteratthis

8YoureworsethanyourDadsjokes

9

10]

11

12defenter(self)

13print(Deathquips[randint(0len(selfquips)-1)])

14exit(1)MyfirstsceneistheoddscenenamedDeath

whichshowsyouthesimplestkindofsceneyoucanwrite

Clickheretoviewcodeimage

ex43py

1classCentralCorridor(Scene)

2

3defenter(self)

4print(dedent(

5TheGothonsofPlanetPercal25haveinvadedyour

shipand

6destroyedyourentirecrewYouarethelast

surviving

7memberandyourlastmissionistogettheneutron

destruct

8bombfromtheWeaponsArmoryputitinthebridge

and

9blowtheshipupaftergettingintoanescapepod

10

11Yourerunningdownthecentralcorridortothe

Weapons

12ArmorywhenaGothonjumpsoutredscalyskin

darkgrimy

13teethandevilclowncostumeflowingaroundhis

hate

14filledbodyHesblockingthedoortotheArmory

and

15abouttopullaweapontoblastyou

16))

17

18action=input(gt)

19

20ifaction==shoot

21print(dedent(

22Quickonthedrawyouyankoutyourblaster

andfire

23itattheGothonHisclowncostumeis

flowingand

24movingaroundhisbodywhichthrowsoffyour

aim

25Yourlaserhitshiscostumebutmisseshim

entirely

26Thiscompletelyruinshisbrandnewcostume

hismother

27boughthimwhichmakeshimflyintoan

insanerage

28andblastyourepeatedlyinthefaceuntil

youare

29deadThenheeatsyou

30))

31returndeath

32

33elifaction==dodge

34print(dedent(

35Likeaworldclassboxeryoudodgeweave

slipand

36sliderightastheGothonsblastercranksa

laser

37pastyourheadInthemiddleofyourartful

dodge

38yourfootslipsandyoubangyourheadonthe

metal

39wallandpassoutYouwakeupshortlyafter

onlyto

40dieastheGothonstompsonyourheadand

eatsyou

41))

42returndeath

43

44elifaction==tellajoke

45print(dedent(

46LuckyforyoutheymadeyoulearnGothon

insultsin

47theacademyYoutelltheoneGothonjoke

youknow

48Lbhezbgurevffbsngjurafurfvgfnebhaq

gurubhfr

49furfvgfnebhaqgurubhfrTheGothonstops

tries

50nottolaughthenbustsoutlaughingand

cantmove

51Whileheslaughingyourunupandshoothim

squarein

52theheadputtinghimdownthenjumpthrough

the

53WeaponArmorydoor

54))

55returnlaser_weapon_armory

56

57else

58print(DOESNOTCOMPUTE)

59returncentral_corridor

AfterthatIrsquovecreatedtheCentralCorridorwhichisthestartofthegameIrsquomdoingthescenesforthegamebeforetheMapbecauseIneedtoreferencethemlaterYoushouldalsoseehowIusethededentfunctiononline4TryremovingitlatertoseewhatitdoesClickheretoviewcodeimage

ex43py

1classLaserWeaponArmory(Scene)

2

3defenter(self)

4print(dedent(

5YoudoadiverollintotheWeaponArmory

crouchandscan

6theroomformoreGothonsthatmightbe

hidingItsdead

7quiettooquietYoustandupandruntothe

farsideof

8theroomandfindtheneutronbombinits

container

9Theresakeypadlockontheboxandyouneed

thecodeto

10getthebomboutIfyougetthecodewrong10

timesthen

11thelockclosesforeverandyoucantgetthe

bombThe

12codeis3digits

13))

14

15code=frandint(19)randint(19)randint(19)

16guess=input([keypad]gt)

17guesses=0

18

19whileguess=codeandguesseslt10

20print(BZZZZEDDD)

21guesses+=1

22guess=input([keypad]gt)

23

24ifguess==code

25print(dedent(

26Thecontainerclicksopenandtheseal

breaksletting

27gasoutYougrabtheneutronbombandrun

asfastas

28youcantothebridgewhereyoumustplace

itinthe

29rightspot

30))

31returnthe_bridge

32else

33print(dedent(

34Thelockbuzzesonelasttimeandthenyou

heara

35sickeningmeltingsoundasthemechanismis

fused

36togetherYoudecidetositthereand

finallythe

37Gothonsblowuptheshipfromtheirshipand

youdie

38))

39returndeath

40

41

42

43classTheBridge(Scene)

44

45defenter(self)

46print(dedent(

47YouburstontotheBridgewiththenetron

destructbomb

48underyourarmandsurprise5Gothonswhoare

tryingto

49takecontroloftheshipEachofthemhasan

evenuglier

50clowncostumethanthelastTheyhavent

pulledtheir

51weaponsoutyetastheyseetheactivebomb

underyour

52armanddontwanttosetitoff

53))

54

55action=input(gt)

56

57ifaction==throwthebomb

58print(dedent(

59Inapanicyouthrowthebombatthegroup

ofGothons

60andmakealeapforthedoorRightasyou

dropita

61Gothonshootsyourightinthebackkilling

youAs

62youdieyouseeanotherGothonfrantically

tryto

63disarmthebombYoudieknowingtheywill

probably

64blowupwhenitgoesoff

65))

66returndeath

67

68elifaction==slowlyplacethebomb

69print(dedent(

70Youpointyourblasteratthebombunder

yourarmand

71theGothonsputtheirhandsupandstartto

sweat

72Youinchbackwardtothedooropenitand

then

73carefullyplacethebombonthefloor

pointingyour

74blasteratitYouthenjumpbackthrough

thedoor

75punchtheclosebuttonandblastthelockso

the

76GothonscantgetoutNowthatthebombis

placed

77youruntotheescapepodtogetoffthis

tincan

78))

79

80returnescape_pod

81else

82print(DOESNOTCOMPUTE)

83returnthe_bridge

84

85

86classEscapePod(Scene)

87

88defenter(self)

89print(dedent(

90Yourushthroughtheshipdesperatelytryingto

makeitto

91theescapepodbeforethewholeship

explodesItseems

92likehardlyanyGothonsareontheshipsoyour

runis

93clearofinterferenceYougettothechamber

withthe

94escapepodsandnowneedtopickoneto

takeSomeof

95themcouldbedamagedbutyoudonthavetimeto

look

96Theres5podswhichonedoyoutake

97))

98

99good_pod=randint(15)

100guess=input([pod]gt)

101

102

103ifint(guess)=good_pod

104print(dedent(

105Youjumpintopodguessandhittheeject

button

106Thepodescapesoutintothevoidofspace

then

107implodesasthehullrupturescrushingyour

bodyinto

108jamjelly

109))

110returndeath

111else

112print(dedent(

113Youjumpintopodguessandhittheeject

button

114Thepodeasilyslidesoutintospaceheading

tothe

115planetbelowAsitfliestotheplanet

youlook

116backandseeyourshipimplodethenexplode

likea

117brightstartakingouttheGothonshipat

thesame

118timeYouwon

119))

120

121returnfinished

122

123classFinished(Scene)

124

125defenter(self)

126print(YouwonGoodjob)

127returnfinished

ThisistherestofthegamersquosscenesandsinceIknowIneedthemandhavethoughtabouthowtheyrsquollflowtogetherIrsquomabletocodethemupdirectlyIncidentallyIwouldnrsquotjusttypeallthiscodeinRememberIsaidtotryandbuildthisincrementallyonelittlebitatatimeIrsquomjustshowingyouthefinalresultClickheretoviewcodeimage

ex43py

1classMap(object)

2

3scenes=

4central_corridorCentralCorridor()

5laser_weapon_armoryLaserWeaponArmory()

6the_bridgeTheBridge()

7escape_podEscapePod()

8deathDeath()

9finishedFinished()

10

11

12def__init__(selfstart_scene)

13selfstart_scene=start_scene

14

15defnext_scene(selfscene_name)

16val=Mapscenesget(scene_name)

17returnval

18

19defopening_scene(self)

20returnselfnext_scene(selfstart_scene)AfterthatI

havemyMapclassandyoucanseeitisstoringeachscenebyname

inadictionaryandthenIrefertothatdictwithMapscenesThis

isalsowhythemapcomesafterthescenesbecausethedictionaryhas

torefertothescenessotheyhavetoexist

Clickheretoviewcodeimage

ex43py

1a_map=Map(central_corridor)

2a_game=Engine(a_map)

3a_gameplay()FinallyIrsquovegotmycodethatrunsthegameby

makingaMapthenhandingthatmaptoanEnginebeforecallingplay

tomakethegamework

WhatYouShouldSeeMakesureyouunderstandthegameandthatyoutriedtosolveityourselffirstOnethingtodoifyoursquorestumpedischeatalittlebyreadingmycodethencontinuetryingtosolveityourselfWhenIrunmygameitlookslikethisClickheretoviewcodeimage

Exercise43Session

$python36ex43py

TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyedyourentirecrewYouarethelastsurviving

memberandyourlastmissionistogettheneutrondestruct

bombfromtheWeaponsArmoryputitinthebridgeand

blowtheshipupaftergettingintoanescapepod

YourerunningdownthecentralcorridortotheWeapons

ArmorywhenaGothonjumpsoutredscalyskindarkgrimy

teethandevilclowncostumeflowingaroundhishate

filledbodyHesblockingthedoortotheArmoryand

abouttopullaweapontoblastyou

gtdodge

Likeaworldclassboxeryoudodgeweaveslipand

sliderightastheGothonsblastercranksalaser

pastyourheadInthemiddleofyourartfuldodge

yourfootslipsandyoubangyourheadonthemetal

wallandpassoutYouwakeupshortlyafteronlyto

dieastheGothonstompsonyourheadandeatsyou

YoureworsethanyourDadsjokes

StudyDrills1ChangeitMaybeyouhatethisgameItcouldbetooviolentormaybeyouarenrsquotintosci-fiGetthegameworkingthenchangeittowhatyoulikeThisisyourcomputeryoumakeitdowhatyouwant

2IhaveabuginthiscodeWhyisthedoorlockguessing11times3Explainhowreturningthenextroomworks4AddcheatcodestothegamesoyoucangetpastthemoredifficultroomsIcandothiswithtwowordsononeline

5GobacktomydescriptionandanalysisthentrytobuildasmallcombatsystemfortheheroandthevariousGothonsheencounters

6ThisisactuallyasmallversionofsomethingcalledaldquofinitestatemachinerdquoReadaboutthemTheymightnotmakesensebuttryanyway

CommonStudentQuestionsWherecanIfindstoriesformyowngamesYoucanmakethemupjustlikeyouwouldtellastorytoafriendOryoucantakesimplescenesfromabookormovieyoulike

Exercise44InheritanceversusComposition

InthefairytalesaboutheroesdefeatingevilvillainstherersquosalwaysadarkforestofsomekindItcouldbeacaveaforestanotherplanetjustsomeplacethateveryoneknowstheheroshouldnrsquotgoOfcourseshortlyafterthevillainisintroducedyoufindoutyestheherohastogotothatstupidforesttokillthebadguyItseemstheherojustkeepsgettingintosituationsthatrequirehimtoriskhislifeinthisevilforestYourarelyreadfairytalesabouttheheroeswhoaresmartenoughtojustavoidthewholesituationentirelyYouneverhearaherosayldquoWaitaminuteifIleavetomakemyfortunesonthehighseasleavingButtercupbehindIcoulddieandthenshersquodhavetomarrysomeuglyprincenamedHumperdinkHumperdinkIthinkIrsquollstayhereandstartaFarmBoyforRentbusinessrdquoIfhedidthattherersquodbenofireswampdyingreanimationswordfightsgiantsoranykindofstoryreallyBecauseofthistheforestinthesestoriesseemstoexistlikeablackholethatdragstheheroinnomatterwhattheydoInobject-orientedprogramminginheritanceistheevilforestExperiencedprogrammersknowtoavoidthisevilbecausetheyknowthatdeepinsidetheDarkForestInheritanceistheEvilQueenMultipleInheritanceShelikestoeatsoftwareandprogrammerswithhermassivecomplexityteethchewingonthefleshofthefallenButtheforestissopowerfulandsotemptingthatnearlyeveryprogrammerhastogointoitandtrytomakeitoutalivewiththeEvilQueenrsquosheadbeforetheycancallthemselvesrealprogrammersYoujustcanrsquotresisttheInheritanceForestrsquospullsoyougoinAftertheadventureyoulearntojuststayoutofthatstupidforestandbringanarmyifyouareeverforcedtogoinagainThisisbasicallyafunnywaytosaythatIrsquomgoingtoteachyousomethingyoushouldusecarefullycalledinheritanceProgrammerswhoarecurrentlyintheforestbattlingtheQueenwillprobablytellyouthatyouhavetogoinTheysaythisbecausetheyneedyourhelpsincewhattheyrsquovecreatedisprobablytoomuchforthemtohandleButyoushouldalwaysrememberthisMostoftheusesofinheritancecanbesimplifiedorreplacedwithcompositionandmultipleinheritanceshouldbeavoidedatallcosts

WhatIsInheritanceInheritanceisusedtoindicatethatoneclasswillgetmostorallofitsfeaturesfromaparentclassThishappensimplicitlywheneveryouwriteclass

Foo(Bar)whichsaysldquoMakeaclassFoothatinheritsfromBarrdquoWhenyoudothisthelanguagemakesanyactionthatyoudooninstancesofFooalsoworkasiftheyweredonetoaninstanceofBarDoingthisletsyouputcommonfunctionalityintheBarclassthenspecializethatfunctionalityintheFooclassasneededWhenyouaredoingthiskindofspecializationtherearethreewaysthattheparentandchildclassescaninteract1Actionsonthechildimplyanactionontheparent

2Actionsonthechildoverridetheactionontheparent3Actionsonthechildaltertheactionontheparent

Iwillnowdemonstrateeachoftheseinorderandshowyoucodeforthem

ImplicitInheritanceFirstIwillshowyoutheimplicitactionsthathappenwhenyoudefineafunctionintheparentbutnotinthechildClickheretoviewcodeimage

ex44apy

1classParent(object)

2

3defimplicit(self)

4print(PARENTimplicit())

5

6classChild(Parent)

7pass

8

9dad=Parent()

10son=Child()

11

12dadimplicit()

13sonimplicit()TheuseofpassundertheclassChildishow

youtellPythonthatyouwantanemptyblockThiscreatesaclass

namedChildbutsaysthattherersquosnothingnewtodefineinit

InsteaditwillinheritallofitsbehaviorfromParentWhenyourun

thiscodeyougetthefollowingExercise44aSession

$python36ex44apy

PARENTimplicit()

PARENTimplicit()NoticehoweventhoughIrsquomcallingsonimplicit()

online13andeventhoughChilddoesnothaveanimplicitfunction

defineditstillworksanditcallstheonedefinedinParentThis

showsyouthatifyouputfunctionsinabaseclass(ieParent)

thenallsubclasses(ieChild)willautomaticallygetthose

featuresVeryhandyforrepetitivecodeyouneedinmanyclasses

OverrideExplicitlyTheproblemwithhavingfunctionscalledimplicitlyissometimesyouwantthechildtobehavedifferentlyInthiscaseyouwanttooverridethefunctioninthechildeffectivelyreplacingthefunctionalityTodothisjustdefineafunctionwiththesamenameinChildHerersquosanexampleClickheretoviewcodeimage

ex44bpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6classChild(Parent)

7

8defoverride(self)

9print(CHILDoverride())

10

11dad=Parent()

12son=Child()

13

14dadoverride()

15sonoverride()InthisexampleIhaveafunctionnamedoverride

inbothclassessoletrsquosseewhathappenswhenIrunit

Exercise44bSession

$python36ex44bpy

PARENToverride()

CHILDoverride()Asyoucanseewhenline14runsitrunsthe

Parentoverridefunctionbecausethatvariable(dad)isaParentBut

whenline15runsitprintsouttheChildoverridemessagesbecause

sonisaninstanceofChildandChildoverridesthatfunctionby

definingitsownversion

Takeabreakrightnowandtryplayingwiththesetwoconceptsbeforecontinuing

AlterBeforeorAfter

AlterBeforeorAfterThethirdwaytouseinheritanceisaspecialcaseofoverridingwhereyouwanttoalterthebehaviorbeforeoraftertheParentclassrsquosversionrunsYoufirstoverridethefunctionjustlikeinthelastexamplebutthenyouuseaPythonbuilt-infunctionnamedsupertogettheParentversiontocallHerersquostheexampleofdoingthatsoyoucanmakesenseofthisdescriptionClickheretoviewcodeimage

ex44cpy

1classParent(object)

2

3defaltered(self)

4print(PARENTaltered())

5

6classChild(Parent)

7

8defaltered(self)

9print(CHILDBEFOREPARENTaltered())

10super(Childself)altered()

11print(CHILDAFTERPARENTaltered())

12

13dad=Parent()

14son=Child()

15

16dadaltered()

17sonaltered()Theimportantlineshereare9ndash11whereinthe

ChildIdothefollowingwhensonaltered()iscalled1Because

IrsquoveoverriddenParentalteredtheChildalteredversionrunsand

line9executeslikeyoursquodexpect

2InthiscaseIwanttodoabeforeandaftersoafterline9IwanttousesupertogettheParentalteredversion

3Online10Icallsuper(Childself)altered()whichisawareofinheritanceandwillgettheParentclassforyouYoushouldbeabletoreadthisasldquocallsuperwithargumentsChildandselfthencallthefunctionalteredonwhateveritreturnsrdquo

4AtthispointtheParentalteredversionofthefunctionrunsandthatprintsouttheParentmessage

5FinallythisreturnsfromtheParentalteredandtheChildalteredfunctioncontinuestoprintouttheaftermessage

IfyourunthisyoushouldseethisClickheretoviewcodeimage

Exercise44cSession

$python36ex44cpy

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

AllThreeCombinedTodemonstratealloftheseIhaveafinalversionthatshowseachkindofinteractionfrominheritanceinonefileClickheretoviewcodeimage

ex44dpy

1classParent(object)

2

3defoverride(self)

4print(PARENToverride())

5

6defimplicit(self)

7print(PARENTimplicit())

8

9defaltered(self)

10print(PARENTaltered())

11

12classChild(Parent)

13

14defoverride(self)

15print(CHILDoverride())

16

17defaltered(self)

18print(CHILDBEFOREPARENTaltered())

19super(Childself)altered()

20print(CHILDAFTERPARENTaltered())

21

22dad=Parent()

23son=Child()

24

25dadimplicit()

26sonimplicit()

27

28dadoverride()

29sonoverride()

30

31dadaltered()

32sonaltered()Gothrougheachlineofthiscodeandwritea

commentexplainingwhatthatlinedoesandwhetheritrsquosanoverride

ornotThenrunitandconfirmyougetwhatyouexpectedClickhere

toviewcodeimage

Exercise44dSession

$python36ex44dpy

PARENTimplicit()

PARENTimplicit()

PARENToverride()

CHILDoverride()

PARENTaltered()

CHILDBEFOREPARENTaltered()

PARENTaltered()

CHILDAFTERPARENTaltered()

TheReasonforsuper()ThisshouldseemlikecommonsensebutthenwegetintotroublewithathingcalledmultipleinheritanceMultipleinheritanceiswhenyoudefineaclassthatinheritsfromoneormoreclasseslikethisClickheretoviewcodeimage

classSuperFun(ChildBadStuff)

passThisislikesayingldquoMakeaclassnamedSuperFunthat

inheritsfromtheclassesChildandBadStuffatthesametimerdquo

InthiscasewheneveryouhaveimplicitactionsonanySuperFuninstancePythonhastolookupthepossiblefunctionintheclasshierarchyforbothChildandBadStuffbutitneedstodothisinaconsistentorderTodothisPythonusesldquomethodresolutionorderrdquo(MRO)andanalgorithmcalledC3togetitstraightBecausetheMROiscomplexandawell-definedalgorithmisusedPythoncanrsquotleaveittoyoutogettheMROrightInsteadPythongivesyouthesuper()functionwhichhandlesallofthisforyouintheplacesthatyouneedthealteringtypeofactionsasIdidinChildalteredWithsuper()youdonrsquothavetoworryaboutgettingthisrightandPythonwillfindtherightfunctionforyou

Usingsuper()with__init__Themostcommonuseofsuper()isactuallyin__init__functionsinbaseclassesThisisusuallytheonlyplacewhereyouneedtodosomethingsina

childthencompletetheinitializationintheparentHerersquosaquickexampleofdoingthatintheChildClickheretoviewcodeimage

classChild(Parent)

def__init__(selfstuff)

selfstuff=stuff

super(Childself)__init__()Thisisprettymuchthesameas

theChildalteredexampleaboveexceptIrsquomsettingsomevariablesin

the__init__beforehavingtheParentinitializewithits

Parent__init__

CompositionInheritanceisusefulbutanotherwaytodotheexactsamethingisjusttouseotherclassesandmodulesratherthanrelyonimplicitinheritanceIfyoulookatthethreewaystoexploitinheritancetwoofthethreeinvolvewritingnewcodetoreplaceoralterfunctionalityThiscaneasilybereplicatedbyjustcallingfunctionsinamoduleHerersquosanexampleofdoingthisClickheretoviewcodeimage

ex44epy

1classOther(object)

2

3defoverride(self)

4print(OTHERoverride())

5

6defimplicit(self)

7print(OTHERimplicit())

8

9defaltered(self)

10print(OTHERaltered())

11

12classChild(object)

13

14def__init__(self)

15selfother=Other()

16

17defimplicit(self)

18selfotherimplicit()

19

20defoverride(self)

21print(CHILDoverride())

22

23defaltered(self)

24print(CHILDBEFOREOTHERaltered())

25selfotheraltered()

26print(CHILDAFTEROTHERaltered())

27

28son=Child()

29

30sonimplicit()

31sonoverride()

32sonaltered()InthiscodeIrsquomnotusingthenameParentsince

thereisnotaparent-childis-arelationshipThisisahas-a

relationshipwhereChildhas-aOtherthatitusestogetitswork

doneWhenIrunthisIgetthefollowingoutputExercise44e

Session

$python36ex44epy

OTHERimplicit()

CHILDoverride()

CHILDBEFOREOTHERaltered()

OTHERaltered()

CHILDAFTEROTHERaltered()Youcanseethatmostofthecodein

ChildandOtheristhesametoaccomplishthesamethingTheonly

differenceisthatIhadtodefineaChildimplicitfunctiontodo

thatoneactionIcouldthenaskmyselfifIneedthisOthertobea

classandcouldIjustmakeitintoamodulenamedotherpy

WhentoUseInheritanceorCompositionThequestionofldquoinheritanceversuscompositionrdquocomesdowntoanattempttosolvetheproblemofreusablecodeYoudonrsquotwanttohaveduplicatedcodealloveryoursoftwaresincethatrsquosnotcleanandefficientInheritancesolvesthisproblembycreatingamechanismforyoutohaveimpliedfeaturesinbaseclassesCompositionsolvesthisbygivingyoumodulesandthecapabilitytocallfunctionsinotherclassesIfbothsolutionssolvetheproblemofreusethenwhichoneisappropriateinwhichsituationsTheanswerisincrediblysubjectivebutIrsquollgiveyoumythreeguidelinesforwhentodowhich1AvoidmultipleinheritanceatallcostsasitrsquostoocomplextobereliableIfyoursquorestuckwithitthenbepreparedtoknowtheclasshierarchyandspendtimefindingwhereeverythingiscomingfrom

2Usecompositiontopackagecodeintomodulesthatareusedinmanydifferentunrelatedplacesandsituations

3Useinheritanceonlywhenthereareclearlyrelatedreusablepiecesofcodethatfitunderasinglecommonconceptorifyouhavetobecauseofsomethingyoursquoreusing

DonotbeaslavetotheserulesThethingtorememberaboutobject-orientedprogrammingisthatitisentirelyasocialconventionprogrammershavecreatedtopackageandsharecodeBecauseitrsquosasocialconventionbutonethatrsquoscodifiedinPythonyoumaybeforcedtoavoidtheserulesbecauseofthepeopleyouworkwithInthatcasefindouthowtheyusethingsandthenjustadapttothesituation

StudyDrillsThereisonlyoneStudyDrillforthisexercisebecauseitisabigexerciseGoandreadhttpwwwpythonorgdevpepspep-0008andstarttryingtouseitinyourcodeYoursquollnoticethatsomeofitisdifferentfromwhatyoursquovebeenlearninginthisbookbutnowyoushouldbeabletounderstandtheirrecommendationsandusetheminyourowncodeTherestofthecodeinthisbookmayormaynotfollowtheseguidelinesdependingonwhetheritmakesthecodemoreconfusingIsuggestyoualsodothisascomprehensionismoreimportantthanimpressingeveryonewithyourknowledgeofesotericstylerules

CommonStudentQuestionsHowdoIgetbetteratsolvingproblemsthatIhavenrsquotseenbeforeTheonlywaytogetbetteratsolvingproblemsistosolveasmanyproblemsasyoucanbyyourselfTypicallypeoplehitadifficultproblemandthenrushouttofindananswerThisisfinewhenyouhavetogetthingsdonebutifyouhavethetimetosolveityourselfthentakethattimeStopandbangyourheadagainsttheproblemforaslongaspossibletryingeverypossiblethinguntilyousolveitorgiveupAfterthattheanswersyoufindwillbemoresatisfyingandyoursquolleventuallygetbetteratsolvingproblems

ArenrsquotobjectsjustcopiesofclassesInsomelanguages(likeJavaScript)thatistrueThesearecalledprototypelanguagesandtherearenotmanydifferencesbetweenobjectsandclassesotherthanusageInPythonhoweverclassesactastemplatesthatldquomintrdquonewobjectssimilartohowcoinsaremintedusingadie(template)

Exercise45YouMakeaGame

YouneedtostartlearningtofeedyourselfHopefullyasyouhaveworkedthroughthisbookyouhavelearnedthatalltheinformationyouneedisontheinternetYoujusthavetogosearchforitTheonlythingyouhavebeenmissingaretherightwordsandwhattolookforwhenyousearchNowyoushouldhaveasenseofitsoitrsquosabouttimeyoustruggledthroughabigprojectandtriedtogetitworkingHereareyourrequirements

1MakeadifferentgamefromtheoneImade2UsemorethanonefileanduseimporttousethemMakesureyouknowwhatthatis

3Useoneclassperroomandgivetheclassesnamesthatfittheirpurposes(likeGoldRoomKoiPondRoom)

4YourrunnerwillneedtoknowabouttheseroomssomakeaclassthatrunsthemandknowsaboutthemTherersquoreplentyofwaystodothisbutconsiderhavingeachroomreturnwhatroomisnextorsettingavariableofwhatroomisnext

OtherthanthatIleaveittoyouSpendawholeweekonthisandmakeitthebestgameyoucanUseclassesfunctionsdictslistsanythingyoucantomakeitniceThepurposeofthislessonistoteachyouhowtostructureclassesthatneedotherclassesinsideotherfilesRememberIrsquomnottellingyouexactlyhowtodothisbecauseyouhavetodothisyourselfGofigureitoutProgrammingisproblemsolvingandthatmeanstryingthingsexperimentingfailingscrappingyourworkandtryingagainWhenyougetstuckaskforhelpandshowpeopleyourcodeIftheyaremeantoyouignorethemandfocusonthepeoplewhoarenotmeanandoffertohelpKeepworkingitandcleaningituntilitrsquosgoodthenshowitsomemoreGoodluckandseeyouinaweekwithyourgame

EvaluatingYourGameInthisexerciseyouwillevaluatethegameyoujustmadeMaybeyougotpartwaythroughitandyougotstuckMaybeyougotitworkingbutjustbarelyEitherwaywersquoregoingtogothroughabunchofthingsyoushouldknownowandmakesureyoucoveredtheminyourgameWersquoregoingtostudyproperlyformattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquo

formattingaclasscommonconventionsinusingclassesandalotofldquotextbookrdquoknowledgeWhywouldIhaveyoutrytodoityourselfandthenshowyouhowtodoitrightFromnowoninthebookIrsquomgoingtotrytomakeyouself-sufficientIrsquovebeenholdingyourhandmostlythiswholetimeandIcanrsquotdothatformuchlongerIrsquomnowinsteadgoingtogiveyouthingstodohaveyoudothemonyourownandthengiveyouwaystoimprovewhatyoudidYouwillstruggleatfirstandprobablybeveryfrustratedbutstickwithitandeventuallyyouwillbuildamindforsolvingproblemsYouwillstarttofindcreativesolutionstoproblemsratherthanjustcopysolutionsoutoftextbooks

FunctionStyleAlltheotherrulesIrsquovetaughtyouabouthowtomakeanicefunctionapplyherebutaddthesethings

bullForvariousreasonsprogrammerscallfunctionsthatarepartofclassesldquomethodsrdquoItrsquosmostlymarketingbutjustbewarnedthateverytimeyousayldquofunctionrdquotheyrsquollannoyinglycorrectyouandsayldquomethodrdquoIftheygettooannoyingjustaskthemtodemonstratethemathematicalbasisthatdetermineshowaldquomethodrdquoisdifferentfromaldquofunctionrdquoandtheyrsquollshutup

bullWhenyouworkwithclassesmuchofyourtimeisspenttalkingaboutmakingtheclassldquodothingsrdquoInsteadofnamingafunctionafterwhatthefunctiondoesinsteadnameitasifitrsquosacommandyouaregivingtotheclassForexamplepopissayingldquoHeylistpopthisoffrdquoItisnrsquotcalledremove_from_end_of_listbecauseeventhoughthatrsquoswhatitdoesthatrsquosnotacommandtoalist

bullKeepyourfunctionssmallandsimpleForsomereasonwhenpeoplestartlearningaboutclassestheyforgetthis

ClassStylebullYourclassshoulduseldquocamelcaserdquoasinSuperGoldFactoryratherthanldquounderscoreformatrdquoasinsuper_gold_factory

bullTrynottodotoomuchinyour__init__functionsItmakesthemhardertouse

bullYourotherfunctionsshoulduseunderscoreformatsowritemy_awesome_hairandnotmyawesomehairorMyAwesomeHair

bullBeconsistentinhowyouorganizeyourfunctionargumentsIfyourclass

hastodealwithusersdogsandcatskeepthatorderthroughoutunlessitreallydoesnrsquotmakesenseIfyouhaveonefunctionthattakes(dogcatuser)andtheothertakes(usercatdog)itrsquollbehardtouse

bullTrynottousevariablesthatcomefromthemoduleorglobalsTheyshouldbefairlyself-contained

bullAfoolishconsistencyisthehobgoblinoflittlemindsConsistencyisgoodbutfoolishlyfollowingsomeidioticmantrabecauseeveryoneelsedoesisbadstyleThinkforyourself

bullAlwaysalwayshaveclassName(object)formatorelseyouwillbeinbigtrouble

CodeStylebullGiveyourcodeverticalspacesopeoplecanreaditYouwillfindsomeverybadprogrammerswhoareabletowritereasonablecodebutwhodonotaddanyspacesThisisbadstyleinanylanguagebecausethehumaneyeandbrainusespaceandverticalalignmenttoscanandseparatevisualelementsNothavingspaceisthesameasgivingyourcodeanawesomecamouflagepaintjob

bullIfyoucanrsquotreaditoutlouditrsquosprobablyhardtoreadIfyouarehavingaproblemmakingsomethingeasytousetryreadingitoutloudNotonlydoesthisforceyoutoslowdownandreallyreaditbutitalsohelpsyoufinddifficultpassagesandthingstochangeforreadability

bullTrytodowhatotherpeoplearedoinginPythonuntilyoufindyourownstyle

bullOnceyoufindyourownstyledonotbeajerkaboutitWorkingwithotherpeoplersquoscodeispartofbeingaprogrammerandotherpeoplehavereallybadtasteTrustmeyouwillprobablyhavereallybadtastetooandnotevenrealizeit

bullIfyoufindsomeonewhowritescodeinastyleyouliketrywritingsomethingthatmimicsthatstyle

GoodCommentsbullProgrammerswilltellyouthatyourcodeshouldbereadableenoughthatyoudonotneedcommentsTheyrsquollthentellyouintheirmostofficialsoundingvoiceldquoErgooneshouldneverwritecommentsordocumentationQEDrdquoThoseprogrammersareeitherconsultantswhogetpaidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendto

paidmoreifotherpeoplecanrsquotusetheircodeorincompetentswhotendtoneverworkwithotherpeopleIgnorethemandwritecomments

bullWhenyouwritecommentsdescribewhyyouaredoingwhatyouaredoingThecodealreadysayshowsowhyyoudidthingsthewayyoudidismoreimportant

bullWhenyouwritedoccommentsforyourfunctionsmakethecommentsdocumentationforsomeonewhowillhavetouseyourcodeYoudonothavetogocrazybutanicelittlesentenceaboutwhatsomeonecandowiththatfunctionhelpsalot

bullWhilecommentsaregoodtoomanyarebadandyouhavetomaintainthemKeepyourcommentsrelativelyshortandtothepointandifyouchangeafunctionreviewthecommenttomakesureitrsquosstillcorrect

EvaluateYourGameIwantyoutonowpretendyouaremeAdoptaverysternlookprintoutyourcodeandtakearedpenandmarkeverymistakeyoufindincludinganythingfromthisexerciseandfromotherguidelinesyoursquovereadsofarOnceyouaredonemarkingyourcodeupIwantyoutofixeverythingyoucameupwithThenrepeatthisacoupleoftimeslookingforanythingthatcouldbebetterUseallthetricksIrsquovegivenyoutobreakyourcodedownintothesmallesttiniestlittleanalysisyoucanThepurposeofthisexerciseistotrainyourattentiontodetailonclassesOnceyouaredonewiththisbitofcodefindsomeoneelsersquoscodeanddothesamethingGothroughaprintedcopyofsomepartofitandpointoutallthemistakesandstyleerrorsyoufindThenfixitandseeifyourfixescanbedonewithoutbreakingthatprogramIwantyoutodonothingbutevaluateandfixcodefortheweekmdashyourowncodeandotherpeoplersquosItrsquollbeprettyhardworkbutwhenyouaredoneyourbrainwillbewiredtightlikeaboxerrsquoshands

Exercise46AProjectSkeleton

ThiswillbewhereyoustartlearninghowtosetupagoodprojectldquoskeletonrdquodirectoryThisskeletondirectorywillhaveallthebasicsyouneedtogetanewprojectupandrunningItwillhaveyourprojectlayoutautomatedtestsmodulesandinstallscriptsWhenyougotomakeanewprojectjustcopythisdirectorytoanewnameandeditthefilestogetstarted

macOSLinuxSetupBeforeyoucanbeginthisexerciseyouneedtoinstallsomesoftwareforPythonbyusingatoolcalledpip36(orjustpip)toinstallnewmodulesThepip36commandshouldbeincludedwithyourpython36installationYoursquollwanttoverifythisusingthiscommand

$pip36list

pip(901)

setuptools(2880)

$

YoucanignoreanydeprecationwarningifyouseeitYoumayalsoseeothertoolsinstalledbutthebaseshouldbepipandsetuptoolsOnceyoursquoveverifiedthisyoucantheninstallvirtualenvClickheretoviewcodeimage

$sudopip36installvirtualenv

Password

Collectingvirtualenv

Downloadingvirtualenvndash1510ndashpy2py3ndashnonendashanywhl(18MB)

100|||||||||||||||||||||||||||||||||18MB11MBs

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

$

ThisisforLinuxormacOSsystemsIfyoursquoreonLinuxmacOSyoursquollwanttorunthefollowingcommandtomakesureyouusethecorrectvirtualenvClickheretoviewcodeimage

$whereisvirtualenv

LibraryFrameworksPythonframeworkVersions36binvirtualenv

YoushouldseesomethingliketheaboveonmacOSbutLinuxwillbevariableOnLinuxyoumighthaveanactualvirtualenv36commandoryoumay

bebetteroffinstallingapackageforitfromyourpackagemanagementsystemOnceyoursquoveinstalledvirtualenvyoucanuseittocreatealdquofakerdquoPythoninstallationwhichmakesiteasiertomanageversionsofyourpackagesfordifferentprojectsFirstrunthiscommandandIrsquollexplainwhatitrsquosdoingClickheretoviewcodeimage

$mkdir~venvs

$virtualenvndashndashsystemndashsitendashpackages~venvslpthw

$~venvslpthwbinactivate

(lpthw)$

Herersquoswhatrsquosgoingonlinebyline1YoucreateadirectorycalledvenvsinyourHOME~tostoreallyourvirtualenvironments

2Yourunvirtualenvandtellittoincludethesystemsitepackages(--system-site-packages)theninstructittobuildthevirtualenvin~venvslpthw

3Youthenldquosourcerdquothelpthwvirtualenvironmentbyusingtheoperatorinbashfollowedbythe~venvslpthwbinactivatescript

4Finallyyourpromptchangestoinclude(lpthw)soyouknowthatyoursquoreusingthatvirtualenvironment

NowyoucanseewherethingsareinstalledClickheretoviewcodeimage

(lpthw)$whichpython

Userszedshawvenvslpthwbinpython

(lpthw)$python

Python360rc2(v360rc2800a67f7806dDec162016141221)

[GCC421(AppleIncbuild5666)(dot3)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

(lpthw)$

YoucanseethatthepythonthatgetsrunisinstalledintheUserszedshawvenvslpthwbinpythondirectoryinsteadoftheoriginallocationThisalsosolvestheproblemofhavingtotypepython36sinceitinstallsbothClickheretoviewcodeimage

$whichpython36

Userszedshawvenvslpthwbinpython36

(lpthw)$

YoursquollfindthesamethingforvirtualenvandpipcommandsThefinalstepinthissetupistoinstallnoseatestingframeworkwersquolluseinthisexerciseClickheretoviewcodeimage

$pipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB32MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)$

Windows10SetupTheWindows10installisalittlesimplerthanonLinuxormacOSbutonlyifyouhaveoneversionofPythoninstalledIfyouhavebothPython36andPython27installedthenyouareonyourownasitismuchtoodifficulttomanagemultipleinstallationsIfyouhavefollowedthebooksofarandhaveonlyPython36thenherersquoswhatyoudoFirstchangetoyourhomedirectoryandconfirmyoursquorerunningtherightversionofpythonClickheretoviewcodeimage

gtcd~

gtpython

Python360(v36041df79263a11Dec232016080612)

[MSCv190064bit(AMD64)]onwin32

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtquit()

Thenyoursquollwanttorunpiptoconfirmyouhaveabasicinstall

gtpiplist

pip(901)

setuptools(2880)

YoucansafelyignoreanydeprecationwarninganditrsquosalrightifyouhaveotherpackagesinstalledNextyoursquollinstallvirtualenvforsettingupsimplevirtualenvironmentsfortherestofthebookClickheretoviewcodeimage

gtpipinstallvirtualenv

Collectingvirtualenv

Usingcachedvirtualenvndash1510ndashpy2py3ndashnonendashanywhl

Installingcollectedpackagesvirtualenv

Successfullyinstalledvirtualenvndash1510

OnceyouhavevirtualenvinstalledyoursquollneedtomakeavenvsdirectoryandfillitwithavirtualenvironmentClickheretoviewcodeimage

gtmkdirvenvs

gtvirtualenvndashndashsystemndashsitendashpackagesvenvslpthw

Usingbaseprefix

cuserszedshappdatalocalprogramspythonpython36

Newpythonexecutablein

CUserszedshawvenvslpthwScriptspythonexe

Installingsetuptoolspipwheeldone

ThosetwocommandscreateavenvsfolderforstoringdifferentvirtualenvironmentsandthencreateyourfirstonenamedlpthwAvirtualenvironment(virtualenv)isaldquofakerdquoplacetoinstallsoftwaresothatyoucanhavedifferentversionsofdifferentpackagesforeachprojectyoursquoreworkingonOnceyouhavethevirtualenvsetupyouneedtoactivateitClickheretoviewcodeimage

gtvenvslpthwScriptsactivate

ThatwillruntheactivatescriptforPowerShellwhichconfiguresthelpthwvirtualenvforyourcurrentshellEverytimeyouwanttouseyoursoftwareforthebookyoursquollrunthiscommandYoursquollnoticeinournextcommandthatthereisnowa(lpthw)addedtothePowerShellpromptshowingyouwhichvirtualenvyoursquoreusingFinallyyoujustneedtoinstallnoseforrunningtestslaterClickheretoviewcodeimage

(lpthw)gtpipinstallnose

Collectingnose

Downloadingnosendash137ndashpy3ndashnonendashanywhl(154kB)

100||||||||||||||||||||||||||||||||||163kB12MBs

Installingcollectedpackagesnose

Successfullyinstallednosendash137

(lpthw)gt

YoursquollseethatthisinstallsnoseexceptpipwillinstallitintoyourvenvslpthwvirtualenvironmentinsteadofthemainsystempackagesdirectoryThisletsyouinstallconflictingversionsofPythonpackagesforeachprojectyouworkonwithoutinfectingyourmainsystemconfiguration

CreatingtheSkeletonProjectDirectoryFirstcreatethestructureofyourskeletondirectorywiththesecommands

$mkdirprojects

$cdprojects

$mkdirskeleton

$cdskeleton

$mkdirbinNAMEtestsdocs

IuseadirectorynamedprojectstostoreallthevariousthingsIrsquomworkingonInsidethatdirectoryIhavemyskeletondirectorythatIputthebasisofmyprojectsintoThedirectoryNAMEwillberenamedtowhateveryouarecallingyourprojectrsquosmainmodulewhenyouusetheskeletonNextweneedtosetupsomeinitialfilesHerersquoshowyoudothatonLinuxmacOS

$touchNAME__init__py

$touchtests__init__py

HerersquosthesamethingonWindowsPowerShellClickheretoviewcodeimage

$newndashitemndashtypefileNAME__init__py

$newndashitemndashtypefiletests__init__py

ThatcreatesanemptyPythonmoduledirectorywecanputourcodeinThenweneedtocreateasetuppyfilewecanusetoinstallourprojectlaterifwewantClickheretoviewcodeimage

setuppy

1try

2fromsetuptoolsimportsetup

3exceptImportError

4fromdistutilscoreimportsetup

5

6config=

7descriptionMyProject

8authorMyName

9urlURLtogetitat

10download_urlWheretodownloadit

11author_emailMyemail

12version01

13install_requires[nose]

14packages[NAME]

15scripts[]

16nameprojectname

17

18

19setup(config)

EditthisfilesothatithasyourcontactinformationandisreadytogoforwhenyoucopyitFinallyyouwillwantasimpleskeletonfilefortestsnamedtestsNAME_testspyClickheretoviewcodeimage

NAME_testspy

1fromnosetoolsimport

2importNAME

3

4defsetup()

5print(SETUP)

6

7defteardown()

8print(TEARDOWN)

9

10deftest_basic()

11print(IRAN)

FinalDirectoryStructureWhenyouaredonesettingallofthisupyourdirectoryshouldlooklikeminehere

skeleton

NAME

__init__py

bin

docs

setuppy

tests

NAME_testspy

__init__py

AndfromnowonyoushouldrunyourcommandsfromthisdirectoryIfyoucanrsquotdols-RandifyoudonrsquotseethissamestructurethenyouareinthewrongplaceForexamplepeoplecommonlygointothetestsdirectoryto

trytorunfilestherewhichwonrsquotworkTorunyourapplicationrsquostestsyouwouldneedtobeabovetestsandthislocationIhaveaboveSoifyoutrythisClickheretoviewcodeimage

$cdtestsWRONGWRONGWRONG

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran0testsin0000s

OK

ThatiswrongYouhavetobeabovetestssoassumingyoumadethismistakeyouwouldfixitbydoingthisClickheretoviewcodeimage

$cdgetoutoftests

$lsCORRECTyouarenowintherightspot

NAMEbindocssetuppytests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0004s

OK

Rememberthisbecausepeoplemakethismistakequitefrequently

WarningAtthetimeofpublicationIlearnedthatthenoseprojecthasbeenabandonedandmightnotworkwellIfyouhavestrangesyntaxerrorswhenyourunnoseteststhenlookattheerroroutputIfitreferencesldquopython27rdquointheoutputthenchancesarenosetestsistryingtorunthe27versionofPythononyourcomputerThesolutionistorunnoseusingpython36-mnoseonLinuxormacOSOnWindowsyoumaynothavethisproblembutusingpython-mnosewillsolveitifyoudo

TestingYourSetupAfteryougetallthatinstalledyoushouldbeabletodothis

$nosetests

$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0007s

OK

IrsquollexplainwhatthisnoseteststhingisdoinginthenextexercisebutfornowifyoudonotseethatyouprobablygotsomethingwrongMakesureyouput__init__pyfilesinyourNAMEandtestsdirectoriesandmakesureyougottestsNAME_testspyright

UsingtheSkeletonYouarenowdonewithmostofyouryakshavingWheneveryouwanttostartanewprojectjustdothis

1MakeacopyofyourskeletondirectoryNameitafteryournewproject2Rename(move)theNAMEdirectorytobethenameofyourprojectorwhateveryouwanttocallyourrootmodule

3Edityoursetuppytohavealltheinformationforyourproject4RenametestsNAME_testspytoalsohaveyourmodulename5Doublecheckitrsquosallworkingbyusingnosetestsagain6Startcoding

RequiredQuizThisexercisedoesnrsquothaveStudyDrillsinsteadherersquosquizyoushouldcomplete

1Readabouthowtouseallofthethingsyouinstalled2ReadaboutthesetuppyfileandallithastoofferWarningItisnotaverywell-writtenpieceofsoftwaresoitwillbeverystrangetouse

3Makeaprojectandstartputtingcodeintothemodulethengetthemoduleworking

4PutascriptinthebindirectorythatyoucanrunReadabouthowyoucanmakeaPythonscriptthatrsquosrunnableforyoursystem

5Mentionthebinscriptyoucreatedinyoursetuppysothatitgetsinstalled

6Useyoursetuppytoinstallyourownmoduleandmakesureitworksthenusepiptouninstallit

CommonStudentQuestions

CommonStudentQuestionsDotheseinstructionsworkonWindowsTheyshouldbutdependingontheversionofWindowsyoumayneedtostrugglewiththesetupabittogetitworkingJustkeepresearchingandtryingituntilyougetitorseeifyoucanaskamoreexperiencedPython+Windowsfriendtohelpout

WhatdoIputintheconfigdictionaryinmysetuppyMakesureyoureadthedocumentationfordistutilsathttpdocspythonorgdistutilssetupscripthtml

IcanrsquotseemtoloadtheNAMEmoduleandjustgetanImportErrorMakesurethatyoumadetheNAME__init__pyfileIfyoursquoreonWindowsmakesureyoudidnrsquotaccidentallynameitNAME__init__pytxtwhichhappensbydefaultwithsomeeditors

WhydoweneedabinfolderatallThisisjustastandardplacetoputscriptsthatarerunonthecommandlinenotaplacetoputmodules

MynosetestsrunonlyshowsonetestbeingrunIsthatrightYesthatrsquoswhatmyoutputshowstoo

Exercise47AutomatedTesting

HavingtotypecommandsintoyourgameoverandovertomakesureitrsquosworkingisannoyingWouldnrsquotitbebettertowritelittlepiecesofcodethattestyourcodeThenwhenyoumakeachangeoraddanewthingtoyourprogramyoujustldquorunyourtestsrdquoandthetestsmakesurethingsarestillworkingTheseautomatedtestswonrsquotcatchallyourbugsbuttheywillcutdownonthetimeyouspendrepeatedlytypingandrunningyourcodeEveryexerciseafterthisonewillnothaveaWhatYouShouldSeesectionbutinsteadwillhaveaWhatYouShouldTestsectionYouwillbewritingautomatedtestsforallofyourcodestartingnowandthiswillhopefullymakeyouanevenbetterprogrammerIwonrsquottrytoexplainwhyyoushouldwriteautomatedtestsIwillonlysaythatyouaretryingtobeaprogrammerandprogrammersautomateboringandtedioustasksTestingapieceofsoftwareisdefinitelyboringandtedioussoyoumightaswellwritealittlebitofcodetodoitforyouThatshouldbealltheexplanationyouneedbecauseyourreasonforwritingunittestsistomakeyourbrainstrongerYouhavegonethroughthisbookwritingcodetodothingsNowyouaregoingtotakethenextleapandwritecodethatknowsaboutothercodeyouhavewrittenThisprocessofwritingatestthatrunssomecodeyouhavewrittenforcesyoutounderstandclearlywhatyouhavejustwrittenItsolidifiesinyourbrainexactlywhatitdoesandwhyitworksandgivesyouanewlevelofattentiontodetail

WritingaTestCaseWersquoregoingtotakeaverysimplepieceofcodeandwriteonesimpletestWersquoregoingtobasethislittletestonanewprojectfromyourprojectskeletonFirstmakeanex47projectfromyourprojectskeletonHerearethestepsyoushouldtakeIrsquomgoingtogivetheseinstructionsinEnglishratherthanshowyouhowtotypethemsothatyouhavetofigureitout

1Copyskeletontoex472RenameeverythingwithNAMEtoex473ChangethewordNAMEinallthefilestoex474Finallyremoveallthepycfilestomakesureyoursquoreclean

ReferbacktoExercise46ifyougetstuckandifyoucanrsquotdothiseasilythen

maybepracticeitafewtimes

WarningRememberthatyourunthecommandnoseteststorunthetestsYoucanrunthemwithpython36ex47_testspybutitwonrsquotworkaseasilyandyoursquollhavetodoitforeachtestfile

Nextcreateasimplefileex47gamepywhereyoucanputthecodetotestThiswillbeaverysillylittleclassthatwewanttotestwiththiscodeinitClickheretoviewcodeimage

gamepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name

5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)Onceyouhavethatfile

changetheunittestskeletontothisClickheretoviewcodeimage

ex47_testspy

1fromnosetoolsimport

2fromex47gameimportRoom

3

4

5deftest_room()

6gold=Room(GoldRoom

7Thisroomhasgoldinityoucangrab

Theresa

8doortothenorth)

9assert_equal(goldnameGoldRoom)

10assert_equal(goldpaths)

11

12deftest_room_paths()

13center=Room(CenterTestroominthecenter)

14north=Room(NorthTestroominthenorth)

15south=Room(SouthTestroominthesouth)

16

17centeradd_paths(northnorthsouthsouth)

18assert_equal(centergo(north)north)

19assert_equal(centergo(south)south)

20

21deftest_map()

22start=Room(StartYoucangowestanddownahole)

23west=Room(TreesTherearetreeshereyoucango

east)

24down=Room(DungeonItsdarkdownhereyoucango

up)

25

26startadd_paths(westwestdowndown)

27westadd_paths(eaststart)

28downadd_paths(upstart)

29

30assert_equal(startgo(west)west)

31assert_equal(startgo(west)go(east)start)

32assert_equal(startgo(down)go(up)start)Thisfile

importstheRoomclassyoumadeintheex47gamemodulesothatyou

candotestsonitThereisthenasetofteststhatarefunctions

startingwithtest_Insideeachtestcasetherersquosabitofcodethat

makesaroomorasetofroomsandthenmakessuretheroomswork

thewayyouexpectthemtoworkIttestsoutthebasicroom

featuresthenthepathsthentriesoutawholemap

Theimportantfunctionshereareassert_equalwhichmakessurethatvariablesyouhavesetorpathsyouhavebuiltinaRoomareactuallywhatyouthinktheyareIfyougetthewrongresultthennosetestswillprintoutanerrormessagesoyoucangofigureitout

TestingGuidelinesFollowthisloosesetofguidelineswhenmakingyourtests

1TestfilesgointestsandarenamedBLAH_testspyotherwisenosetestswonrsquotrunthemThisalsokeepsyourtestsfromclashingwithyourothercode

2Writeonetestfileforeachmoduleyoumake3Keepyourtestcases(functions)shortbutdonotworryiftheyareabitmessyTestcasesareusuallykindofmessy

4EventhoughtestcasesaremessytrytokeepthemcleanandremoveanyrepetitivecodeyoucanCreatehelperfunctionsthatgetridofduplicatecodeYouwillthankmelaterwhenyoumakeachangeandthenhaveto

codeYouwillthankmelaterwhenyoumakeachangeandthenhavetochangeyourtestsDuplicatedcodewillmakechangingyourtestsmoredifficult

5FinallydonotgettooattachedtoyourtestsSometimesthebestwaytoredesignsomethingistojustdeleteitandstartover

WhatYouShouldSeeClickheretoviewcodeimage

Exercise47Session

$nosetests

---------------------------------------------------------------------

-

Ran3testsin0008s

OK

ThatrsquoswhatyoushouldseeifeverythingisworkingrightTrycausinganerrortoseewhatthatlookslikeandthenfixit

StudyDrills1Goreadaboutnosetestsmoreandalsoreadaboutalternatives2LearnaboutPythonrsquosldquodoctestsrdquoandseeifyoulikethembetter3Makeyourroommoreadvancedandthenuseittorebuildyourgameyetagainbutthistimeunittestasyougo

CommonStudentQuestionsIgetasyntaxerrorwhenIrunnosetestsIfyougetthatthenlookatwhattheerrorsaysandfixthatlineofcodeortheonesaboveitToolslikenosetestsarerunningyourcodeandthetestcodesotheywillfindsyntaxerrorsthesameasrunningPythonwill

Icanrsquotimportex47gameMakesureyoucreatetheex47__init__pyfileRefertoExercise46againtoseehowitrsquosdoneIfthatrsquosnottheproblemthendothisonmacOSLinuxexportPYTHONPATH=AndonWindowsClickheretoviewcodeimage

$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

FinallymakesureyoursquorerunningthetestswithnosetestsnotwithjustPython

IgetUserWarningwhenIrunnosetestsYouprobablyhavetwoversionsofPythoninstalledoryouarenrsquotusingdistributeGobackandinstalldistributeorpipasIdescribeinExercise46

Exercise48AdvancedUserInput

InpastgamesyouhandledtheuserrsquosinputbysimplyexpectingsetstringsIftheusertypedldquorunrdquoandexactlyldquorunrdquothenthegameworkedIftheytypedinsimilarphraseslikeldquorunfastrdquoitwouldfailWhatweneedisadevicethatletsuserstypephrasesinvariouswaysandthenconvertthatintosomethingthecomputerunderstandsForexamplewersquodliketohaveallofthesephrasesworkthesamebullopendoorbullopenthedoorbullgoTHROUGHthedoorbullpunchbearbullPunchTheBearintheFACEItshouldbealrightforausertowritesomethingalotlikeEnglishforyourgameandhaveyourgamefigureoutwhatitmeansTodothiswersquoregoingtowriteamodulethatdoesjustthatThismodulewillhaveafewclassesthatworktogethertohandleuserinputandconvertitintosomethingyourgamecanworkwithreliablyAsimplifiedversionoftheEnglishlanguagecouldincludethefollowingelementsbullWordsseparatedbyspacesbullSentencescomposedofthewordsbullGrammarthatstructuresthesentencesintomeaningThatmeansthebestplacetostartisfiguringouthowtogetwordsfromtheuserandwhatkindsofwordsthoseare

OurGameLexiconInourgamewehavetocreatealistofallowablewordscalledaldquolexiconrdquo

bullDirectionwordsnorthsoutheastwestdownupleftrightbackbullVerbsgostopkilleatbullStopwordstheinoffromatitbullNounsdoorbearprincesscabinetbullNumbersanystringof0through9charactersWhenwegettonounswehaveaslightproblemsinceeachroomcouldhaveadifferentsetofnounsbutletrsquosjustpickthissmallsettoworkwithfornowandimproveitlater

BreakingUpaSentenceOncewehaveourlexiconweneedawaytobreakupsentencessothatwecanfigureoutwhattheyareInourcasewersquovedefinedasentenceasldquowordsseparatedbyspacesrdquosowereallyjustneedtodothis

stuff=input(gt)

words=stuffsplit()Thatrsquosallwersquollworryaboutfornowbutthis

willworkreallywellforquiteawhile

LexiconTuples

LexiconTuplesOnceweknowhowtobreakupasentenceintowordswejusthavetogothroughthelistofwordsandfigureoutwhatldquotyperdquotheyareTodothatwersquoregoingtouseahandylittlePythonstructurecalledaldquotuplerdquoAtupleisnothingmorethanalistthatyoucanrsquotmodifyItrsquoscreatedbyputtingdatainsideasetofparentheseswithacommalikealistClickheretoviewcodeimage

first_word=(verbgo)

second_word=(directionnorth)

third_word=(directionwest)

sentence=[first_wordsecond_wordthird_word]

Thiscreatesapair(TYPEWORD)thatletsyoulookatthewordanddothingswithitThisisjustanexamplebutthatrsquosbasicallytheendresultYouwanttotakerawinputfromtheusercarveitintowordswithsplitanalyzethosewordstoidentifytheirtypesandfinallymakeasentenceoutofthem

ScanningInputNowyouarereadytowriteyourscannerThisscannerwilltakeastringofrawinputfromauserandreturnasentencethatrsquoscomposedofalistoftupleswiththe(TOKENWORD)pairingsIfawordisnrsquotpartofthelexiconthenitshouldstillreturntheWORDbutsettheTOKENtoanerrortokenTheseerrortokenswilltelluserstheymessedupHerersquoswhereitgetsfunIrsquomnotgoingtotellyouhowtodothisInsteadIrsquomgoingtowritealdquounittestrdquoandyouaregoingtowritethescannersothattheunittestworks

ExceptionsandNumbersThereisonetinythingIwillhelpyouwithfirstandthatrsquosconvertingnumbersInordertodothisthoughwersquoregoingtocheatanduseexceptionsAnexceptionisanerrorthatyougetfromsomefunctionyoumayhaverunWhathappensisyourfunctionldquoraisesrdquoanexceptionwhenitencountersanerrorthenyouhavetohandlethatexceptionForexampleifyoutypethisintoPythonyougetanexceptionClickheretoviewcodeimage

Exercise48PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtint(hell)

Traceback(mostrecentcalllast)

Fileltstdingtline1inltmodulegt

ValueErrorinvalidliteralforint()withbase10hell

ThatValueErrorisanexceptionthattheint()functionthrewbecausewhatyouhandedint()isnotanumberTheint())functioncouldhavereturnedavaluetotellyouithadanerrorbutsinceitonlyreturnsintegersitrsquodhaveahardtimedoingthatItcanrsquotreturn-1sincethatrsquosanumberInsteadoftryingtofigureoutwhattoreturnwhentherersquosanerrortheint()functionraisestheValueErrorexceptionandyoudealwithitYoudealwithanexceptionbyusingthetryandexceptkeywordsex48_convertpy

1defconvert_number(s)

2try

3returnint(s)

4exceptValueError

5returnNoneYouputthecodeyouwanttoldquotryrdquoinside

thetryblockandthenyouputthecodetorunfortheerrorinside

theexceptInthiscasewewanttoldquotryrdquotocallint()onsomething

thatmightbeanumberIfthathasanerrorthenweldquocatchrdquoitand

returnNone

InyourscannerthatyouwriteyoushouldusethisfunctiontotestwhethersomethingisanumberYoushouldalsodoitasthelastthingyoucheckforbeforedeclaringthatwordanerrorword

ATestFirstChallengeTestfirstisaprogrammingtacticwhereyouwriteanautomatedtestthatpretendsthecodeworksthenyouwritethecodetomakethetestactuallyworkThismethodworkswhenyoucanrsquotvisualizehowthecodeisimplementedbutyoucanimaginehowyouhavetoworkwithitForexampleifyouknowhowyouneedtouseanewclassinanothermodulebutyoudonrsquotquiteknowhowtoimplementthatclassyetthenwritethetestfirstYouaregoingtotakeatestIgiveyouanduseittowritethecodethatmakesitworkTodothisexercisefollowthisprocedure1CreateonesmallpartofthetestIgiveyou

2Makesureitrunsandfailssoyouknowthatthetestisactuallyconfirmingafeatureworks

3Gotoyoursourcefilelexiconpyandwritethecodethatmakesthistestpass

4RepeatuntilyouhaveimplementedeverythinginthetestWhenyougettostep3itrsquosalsogoodtocombineourothermethodofwritingcode1Maketheldquoskeletonrdquofunctionorclassthatyouneed

2Writecommentsinsidedescribinghowthatfunctionworks3Writethecodethatdoeswhatthecommentsdescribe4Removeanycommentsthatjustrepeatthecode

ThismethodofwritingcodeiscalledldquopsuedocoderdquoandworkswellifyoudonrsquotknowhowtoimplementsomethingbutyoucandescribeitinyourownwordsCombiningtheldquotestfirstrdquowiththeldquopsuedocoderdquotacticswehavethissimpleprocessforprogramming1Writeabitoftestthatfails

2Writetheskeletonfunctionmoduleclassthetestneeds3Filltheskeletonwithcommentsinyourownwordsexplaininghowitworks

4Replacethecommentswithcodeuntilthetestpasses5Repeat

InthisexerciseyouwillpracticethismethodofworkingbymakingatestIgiveyourunagainstthelexiconpymodule

WhatYouShouldTestHereisthetestcasetestslexicon_testspythatyoushouldusebutdonrsquottypethisinyetClickheretoviewcodeimage

lexicon_testspy

1fromnosetoolsimport

2fromex48importlexicon

3

4

5deftest_directions()

6assert_equal(lexiconscan(north)[(direction

north)])

7result=lexiconscan(northsoutheast)

8assert_equal(result[(directionnorth)

9(directionsouth)

10(directioneast)])

11

12deftest_verbs()

13assert_equal(lexiconscan(go)[(verbgo)])

14result=lexiconscan(gokilleat)

15assert_equal(result[(verbgo)

16(verbkill)

17(verbeat)])

18

19

20deftest_stops()

21assert_equal(lexiconscan(the)[(stopthe)])

22result=lexiconscan(theinof)

23assert_equal(result[(stopthe)

24(stopin)

25(stopof)])

26

27

28deftest_nouns()

29assert_equal(lexiconscan(bear)[(nounbear)])

30result=lexiconscan(bearprincess)

31assert_equal(result[(nounbear)

32(nounprincess)])

33

34deftest_numbers()

35assert_equal(lexiconscan(1234)[(number1234)])

36result=lexiconscan(391234)

37assert_equal(result[(number3)

38(number91234)])

39

40

41deftest_errors()

42assert_equal(lexiconscan(ASDFADFASDF)

43[(errorASDFADFASDF)])

44result=lexiconscan(bearIASprincess)

45assert_equal(result[(nounbear)

46(errorIAS)

47(nounprincess)])Youwillwant

tocreateanewprojectusingtheprojectskeletonjustlikeyoudid

inExercise47Thenyoursquollneedtocreatethistestcaseandthe

lexiconpyfileitwilluseLookatthetopofthetestcasetosee

howitrsquosbeingimportedtofigureoutwhereitgoes

NextfollowtheprocedureIgaveyouandwritealittlebitofthetestcaseatatimeForexampleherersquoshowIrsquoddoit1WritetheimportatthetopGetthattowork

2Createanemptyversionofthefirsttestcasetest_directionsMakesurethatruns

3Writethefirstlineofthetest_directionstestcaseMakeitfail4Gotothelexiconpyfileandcreateanemptyscanfunction5Runthetestandmakesurescanisatleastrunningeventhoughitfails6Fillinpsuedocodecommentsforhowscanshouldworktomaketest_directionspass

7Writethecodethatmatchesthecommentsuntiltest_directionspasses

8Gobacktotest_directionsandwritetherestofthelines9Gobacktoscaninlexiconpyandworkonittomakethisnewtestcodepass

10Onceyoursquovedonethatyouhaveyourfirstpassingtestandyoumoveontothenexttest

AslongasyoukeepfollowingthisprocedureonelittlechunkatatimeyoucansuccessfullyturnalargeproblemintosmallersolvableproblemsItrsquoslikeclimbingamountainbyturningitintoabunchoflittlehills

StudyDrills1Improvetheunittesttomakesureyoutestmoreofthelexicon2Addtothelexiconandthenupdatetheunittest3MakesureyourscannerhandlesuserinputinanycapitalizationandcaseUpdatethetesttomakesurethisactuallyworks

4Findanotherwaytoconvertthenumber5Mysolutionwas37lineslongIsyourslongerShorter

CommonStudentQuestionsWhydoIkeepgettingImportErrorsImporterrorsareusuallycausedbyfourthings1Youdidnrsquotmakean__init__pyinadirectorythathasmodulesinit2Youareinthewrongdirectory3Youareimportingthewrongmodulebecauseyouspelleditwrong4YourPYTHONPATHisnrsquotsettosoyoucanrsquotloadmodulesfromyourcurrentdirectory

Whatrsquosthedifferencebetweentry-exceptandif-elseThe

try-exceptconstructisonlyusedforhandlingexceptionsthatmodulescanthrowItshouldneverbeusedasanalternativetoif-else

IsthereawaytokeepthegamerunningwhiletheuseriswaitingtotypeIrsquomassumingyouwanttohaveamonsterattackusersiftheydonrsquotreactquicklyenoughItispossiblebutitinvolvesmodulesandtechniquesthatareoutsideofthisbookrsquosdomain

Exercise49MakingSentences

WhatweshouldbeabletogetfromourlittlegamelexiconscannerisalistthatlookslikethisClickheretoviewcodeimage

Exercise49PythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48importlexicon

gtgtgtlexiconscan(gonorth)

[(verbgo)(directionnorth)]

gtgtgtlexiconscan(killtheprincess)

[(verbkill)(stopthe)(nounprincess)]

gtgtgtlexiconscan(eatthebear)

[(verbeat)(stopthe)(nounbear)]

Thiswillalsoworkonlongersentencessuchaslexiconscan(openthedoorandsmackthebearinthenose)NowletusturnthisintosomethingthegamecanworkwithwhichwouldbesomekindofSentenceclassIfyouremembergradeschoolasentencecanbeasimplestructurelikeSubjectVerbObjectObviouslyitgetsmorecomplexthanthatandyouprobablydidmanydaysofannoyingsentencediagramsforEnglishclassWhatwewantistoturntheprecedinglistsoftuplesintoaniceSentenceobjectthathassubjectverbandobject

MatchandPeekTodothisweneedfivetools

1AwaytoloopthroughthelistofscannedwordsThatrsquoseasy2AwaytoldquomatchrdquodifferenttypesoftuplesthatweexpectinourSubjectVerbObjectsetup

3Awaytoldquopeekrdquoatapotentialtuplesowecanmakesomedecisions4Awaytoldquoskiprdquothingswedonotcareaboutlikestopwords5ASentenceobjecttoputtheresultsin

Wewillbeputtingthesefunctionsinamodulenamedex48parserinafilenamedex48parserpyinordertotestitWeusethepeekfunctiontosay

ldquolookatthenextelementinourtuplelistandthenmatchtotakeoneoffandworkwithitrdquo

TheSentenceGrammarBeforeyoucanwritethecodeyouneedtounderstandhowbasicEnglishsentencegrammarworksInourparserwewanttoproduceaSentenceobjectthathasthreeattributes

SentencesubjectThisisthesubjectofanysentencebutcoulddefaulttoldquoplayerrdquomostofthetimesinceasentenceofldquorunnorthrdquoisimplyingldquoplayerrunnorthrdquoThiswillbeanoun

SentenceverbThisistheactionofthesentenceInldquorunnorthrdquoitwouldbeldquorunrdquoThiswillbeaverb

SentenceobjectThisisanothernounthatreferstowhattheverbisdoneonInourgameweseparateoutdirectionswhichwouldalsobeobjectsInldquorunnorthrdquothewordldquonorthrdquowouldbetheobjectInldquohitbearrdquothewordldquobearrdquowouldbetheobject

OurparserthenhastousethefunctionswedescribedandgivenascannedsentenceconvertitintoanListofSentenceobjectstomatchtheinput

AWordonExceptionsYoubrieflylearnedaboutexceptionsbutnothowtoraisethemThiscodedemonstrateshowtodothatwiththeParserErroratthetopNoticethatitusesclassestogiveitthetypeofExceptionAlsonoticetheuseoftheraisekeywordtoraisetheexceptionInyourtestsyouwillwanttoworkwiththeseexceptionswhichIrsquollshowyouhowtodo

TheParserCodeIfyouwantanextrachallengestoprightnowandtrytowritethisbasedonjustmydescriptionIfyougetstuckyoucancomebackandseehowIdiditbuttryingtoimplementtheparseryourselfisgoodpracticeIwillnowwalkthroughthecodesoyoucanenteritintoyourex48parserpyWestarttheparserwiththeexceptionweneedforaparsingerrorClickheretoviewcodeimage

parserpy

1classParserError(Exception)

2pass

ThisishowyoumakeyourownParserErrorexceptionclassyoucanthrowNextweneedtheSentenceobjectwersquollcreateClickheretoviewcodeimage

parserpy

1classSentence(object)

2

3def__init__(selfsubjectverbobj)

4rememberwetake(nounprincess)tuplesand

convertthem

5selfsubject=subject[1]

6selfverb=verb[1]

7selfobject=obj[1]

TherersquosnothingspecialaboutthiscodesofarYoursquorejustmakingsimpleclassesInourdescriptionoftheproblemweneedafunctionthatcanpeekatalistofwordsandreturnwhattypeofworditisClickheretoviewcodeimage

parserpy

1defpeek(word_list)

2ifword_list

3word=word_list[0]

4returnword[0]

5else

6returnNoneWeneedthisfunctionbecausewersquollhaveto

makedecisionsaboutwhatkindofsentencewersquoredealingwithbased

onwhatthenextwordisThenwecancallanotherfunctionto

consumethatwordandcarryon

ToconsumeawordweusethematchfunctionwhichconfirmsthattheexpectedwordistherighttypetakesitoffthelistandreturnsthewordClickheretoviewcodeimage

parserpy

1defmatch(word_listexpecting)

2ifword_list

3word=word_listpop(0)

4

5ifword[0]==expecting

6returnword

7else

8returnNone

9else

10returnNoneAgainthisisfairlysimplebutmakesure

youunderstandthiscodeAlsomakesureyouunderstandwhyIrsquomdoing

itthiswayIneedtopeekatwordsinthelisttodecidewhatkind

ofsentenceIrsquomdealingwithandthenIneedtomatchthosewordsto

createmySentence

ThelastthingIneedisawaytoskipwordsthatarenrsquotusefultotheSentenceThesearethewordslabeledldquostopwordsrdquo(typestop)thatarewordslikeldquotherdquoldquoandrdquoandldquoardquoClickheretoviewcodeimage

parserpy

1defskip(word_listword_type)

2whilepeek(word_list)==word_type

3match(word_listword_type)Rememberthatskipdoesnrsquot

skiponeworditskipsasmanywordsofthattypeasitfindsThis

makesitsoifsomeonetypesldquoscreamatthebearrdquoyougetldquoscreamrdquo

andldquobearrdquo

ThatrsquosourbasicsetofparsingfunctionsandwiththatwecanactuallyparsejustaboutanytextwewantOurparserisverysimplethoughsotheremainingfunctionsareshortFirstwecanhandleparsingaverbClickheretoviewcodeimage

parserpy

1defparse_verb(word_list)

2skip(word_liststop)

3

4ifpeek(word_list)==verb

5returnmatch(word_listverb)

6else

7raiseParserError(Expectedaverbnext)Weskipany

stopwordsthenpeekaheadtomakesurethenextwordisaldquoverbrdquo

typeIfitrsquosnotthenraisetheParserErrortosaywhyIfitisa

ldquoverbrdquothenmatchitwhichtakesitoffthelistAsimilar

functionhandlessentenceobjectsClickheretoviewcodeimage

parserpy

1defparse_object(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==direction

8returnmatch(word_listdirection)

9else

10raiseParserError(Expectedanounordirectionnext)

Againskipthestopwordspeekaheadanddecideifthesentenceis

correctbasedonwhatrsquosthereIntheparse_objectfunctionthough

weneedtohandlebothldquonounrdquoandldquodirectionrdquowordsaspossible

objectsSubjectsarethensimilaragainbutsincewewanttohandle

theimpliedldquoplayerrdquonounwehavetousepeekClickheretoview

codeimage

parserpy

1defparse_subject(word_list)

2skip(word_liststop)

3next_word=peek(word_list)

4

5ifnext_word==noun

6returnmatch(word_listnoun)

7elifnext_word==verb

8return(nounplayer)

9else

10raiseParserError(Expectedaverbnext)Withthat

alloutofthewayandreadyourfinalparse_sentencefunctionis

verysimpleClickheretoviewcodeimage

parserpy

1defparse_sentence(word_list)

2subj=parse_subject(word_list)

3verb=parse_verb(word_list)

4obj=parse_object(word_list)

5

6returnSentence(subjverbobj)

PlayingwiththeParserToseehowthisworksyoucanplaywithitlikethis

ToseehowthisworksyoucanplaywithitlikethisClickheretoviewcodeimage

Exercise49aPythonSession

Python360(defaultFeb22017124829)

[GCC421CompatibleAppleLLVM702(clang-700181)]ondarwin

Typehelpcopyrightcreditsorlicenseformore

information

gtgtgtfromex48parserimport

gtgtgtx=parse_sentence([(verbrun)(directionnorth)])

gtgtgtxsubject

player

gtgtgtxverb

run

gtgtgtxobject

north

gtgtgtx=parse_sentence([(nounbear)(verbeat)(stop

the)

(nounhoney)])

gtgtgtxsubject

bear

gtgtgtxverb

eat

gtgtgtxobject

honey

TrytomapsentencestothecorrectpairingsinasentenceForexamplehowwouldyousayldquothebearrunsouthrdquo

WhatYouShouldTestForExercise49writeacompletetestthatconfirmseverythinginthiscodeisworkingPutthetestintestsparser_testspysimilartothetestfilefromthelastexerciseThatincludesmakingexceptionshappenbygivingtheparserbadsentencesCheckforanexceptionbyusingthefunctionassert_raisesfromthenosedocumentationLearnhowtousethissoyoucanwriteatestthatisexpectedtofailwhichisveryimportantintestingLearnaboutthisfunction(andothers)byreadingthenosedocumentationWhenyouaredoneyoushouldknowhowthisbitofcodeworksandhowtowriteatestforotherpeoplersquoscodeeveniftheydonotwantyoutoTrustmeitrsquosaveryhandyskilltohave

StudyDrills

StudyDrills1Changetheparse_methodsandtrytoputthemintoaclassratherthanusethemjustasmethodsWhichdesigndoyoulikebetter

2Maketheparsermoreerror-resistantsothatyoucanavoidannoyingyourusersiftheytypewordsyourlexicondoesnrsquotunderstand

3Improvethegrammarbyhandlingmorethingslikenumbers4ThinkabouthowyoumightusethisSentenceclassinyourgametodomorefunthingswithauserrsquosinput

CommonStudentQuestionsIcanrsquotseemtomakeassert_raisesworkrightMakesureyouarewritingassert_raises(exceptioncallableparameters)andnotwritingassert_raises(exceptioncallable(parameters))Noticehowthesecondformiscallingthefunctionthenpassingtheresulttoassert_raiseswhichiswrongYouhavetopassthefunctiontocallanditsargumentstoassert_raises

Exercise50YourFirstWebsite

ThesefinalthreeexerciseswillbeveryhardandyoushouldtakeyourtimewiththemInthisfirstoneyoursquollbuildasimplewebversionofoneofyourgamesBeforeyouattemptthisexerciseyoumusthavecompletedExercise46successfullyandhaveaworkingpipinstalledsuchthatyoucaninstallpackagesandknowhowtomakeaskeletonprojectdirectoryIfyoudonrsquotrememberhowtodothisgobacktoExercise46anddoitalloveragain

InstallingflaskBeforecreatingyourfirstwebapplicationyoursquollfirstneedtoinstalltheldquowebframeworkrdquocalledflaskThetermldquoframeworkrdquogenerallymeansldquosomepackagethatmakesiteasierformetodosomethingrdquoIntheworldofwebapplicationspeoplecreateldquowebframeworksrdquotocompensateforthedifficultproblemstheyrsquoveencounteredwhenmakingtheirownsitesTheysharethesecommonsolutionsintheformofapackageyoucandownloadtobootstrapyourownprojectsInourcasewersquollbeusingtheflaskframeworkbuttherearemanymanymanyothersyoucanchoosefromFornowlearnflaskthenbranchouttoanotheronewhenyoursquoreready(orjustkeepusingflasksinceitrsquosgoodenough)UsingpipinstallflaskClickheretoviewcodeimage

$sudopipinstallflask

[sudo]passwordforzedshaw

Downloadingunpackingflask

Runningsetuppyegg_infoforpackageflask

Installingcollectedpackagesflask

Runningsetuppyinstallforflask

Successfullyinstalledflask

Cleaningup

ThiswillworkonLinuxandmacOScomputersbutonWindowsjustdropthesudopartofthepipinstallcommandanditshouldworkIfnotgobacktoExercise46andmakesureyoucandoitreliably

MakeaSimpleldquoHelloWorldrdquoProject

NowyoursquoregoingtomakeaninitialverysimpleldquoHelloWorldrdquowebapplicationandprojectdirectoryusingflaskFirstmakeyourprojectdirectoryClickheretoviewcodeimage

$cdprojects

$mkdirgothonweb

$cdgothonweb

$mkdirbingothonwebtestsdocstemplates

$touchgothonweb__init__py

$touchtests__init__py

YoursquollbetakingthegamefromExercise43andmakingitintoawebapplicationsothatrsquoswhyyoursquorecallingitgothonwebBeforeyoudothatweneedtocreatethemostbasicflaskapplicationpossiblePutthefollowingcodeintoapppyClickheretoviewcodeimage

ex50py

1fromflaskimportFlask

2app=Flask(__name__)

3

4approute()

5defhello_world()

6returnHelloWorld

7

8if__name__==__main__

9apprun()ThenruntheapplicationlikethisClickhereto

viewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)Finally

useyourwebbrowserandgotohttplocalhost5000andyoushould

seetwothingsFirstinyourbrowseryoursquollseeHelloworld

SecondyoursquollseeyourTerminalwithnewoutputlikethisClick

heretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

127001ndashndash[22Feb2017142850]GETHTTP11200ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

127001ndashndash[22Feb2017142850]GETfaviconicoHTTP11404ndash

ThosearelogmessagesthatflaskprintsoutsoyoucanseethattheserverisworkingandwhatthebrowserisdoingbehindthescenesThelogmessageshelpyoudebugandfigureoutwhenyouhaveproblemsForexampleitrsquossayingthatyourbrowsertriedtogetfaviconicobutthatfiledidnrsquotexistsoit

returnedthe404NotFoundstatuscodeIhavenrsquotexplainedthewayanyofthiswebstuffworksyetbecauseIwanttogetyousetupandreadytorollsothatIcanexplainitbetterinthenexttwoexercisesToaccomplishthisIrsquollhaveyoubreakyourflaskapplicationinvariouswaysandthenrestructureitsothatyouknowhowitrsquossetup

WhatrsquosGoingOnHerersquoswhatrsquoshappeningwhenyourbrowserhitsyourapplication

1YourbrowsermakesanetworkconnectiontoyourowncomputerwhichiscalledlocalhostandisastandardwayofsayingldquowhatevermyowncomputeriscalledonthenetworkrdquoItalsousesport5000

2OnceitconnectsitmakesanHTTPrequesttotheapppyapplicationandasksfortheURLwhichiscommonlythefirstURLonanywebsite

3InsideapppyyoursquovegotalistofURLsandwhatfunctionstheymatchTheonlyonewehaveistheindexmappingThismeansthatwheneversomeonegoestowithabrowserflaskwillfindthedefindexandrunittohandletherequest

4NowthatflaskhasfounddefindexitcallsittoactuallyhandletherequestThisfunctionrunsandsimplyreturnsastringforwhatflaskshouldsendtothebrowser

5Finallyflaskhashandledtherequestandsendsthisresponsetothebrowserwhichiswhatyouareseeing

MakesureyoureallyunderstandthisDrawupadiagramofhowthisinformationflowsfromyourbrowsertoflaskthentodefindexandbacktoyourbrowser

FixingErrorsFirstdeleteline8whereyouassignthegreetingvariablethenhitrefreshinyourbrowserThenuseCTRL-CtokillflaskandstartitagainOnceitrsquosrunningagainrefreshyourbrowserandyoushouldseeanldquoInternalServerErrorrdquoBackinyourTerminalyoursquollseethis([VENV]isthepathtoyourvenvsdirectory)Clickheretoviewcodeimage

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

[2017ndash02ndash22143554256]ERRORinappExceptionon[GET]

Traceback(mostrecentcalllast)

File[VENV]site-packagesflaskapppy

line1982inwsgi_app

response=selffull_dispatch_request()

File[VENV]site-packagesflaskapppy

line1614infull_dispatch_request

rv=selfhandle_user_exception(e)

File[VENV]site-packagesflaskapppy

line1517inhandle_user_exception

reraise(exc_typeexc_valuetb)

File[VENV]site-packagesflask_compatpy

line33inreraise

raisevalue

File[VENV]site-packagesflaskapppy

line1612infull_dispatch_request

rv=selfdispatch_request()

File[VENV]site-packagesflaskapppy

line1598indispatch_request

returnselfview_functions[ruleendpoint](reqview_args)

Fileapppyline8inindex

returnrender_template(indexhtmlgreeting=greeting)

NameErrornamegreetingisnotdefined

127001ndashndash[22Feb2017143554]GETHTTP11500ndash

ThisworkswellenoughbutyoucanalsorunflaskinldquodebuggermoderdquoThiswillgiveyouabettererrorpageandmoreusefulinformationTheproblemwithdebuggermodeisitrsquosnotsafetorunontheinternetsoyouhavetoexplicitlyturnitonlikethisClickheretoviewcodeimage

(lpthw)$exportFLASK_DEBUG=1

(lpthw)$python36apppy

Runningonhttp1270015000(PressCTRL+Ctoquit)

Restartingwithstat

Debuggerisactive

Debuggerpincode222ndash752ndash342

Afterthisyouhitrefreshinyourbrowserandyougetamuchmoredetailedpagewithinformationyoucanusetodebugtheapplicationandaliveconsoletoworkwithtofindoutmore

WarningItrsquostheflasklivedebuggingconsoleandtheimprovedoutputthatmakesdebugmodesodangerousontheinternetWiththisinformationanattackercancompletelycontrolyourmachineremotelyIfyoueverdoplaceyourwebapplicationontheinternetdonotactivatedebuggermodeInfactIwouldavoid

makingFLASK_DEBUGeasytoactivateItrsquostemptingtosimplyhackthisstartupsothatyousaveastepduringdevelopmentbutthenthathackwillgetontoyourwebserveranditrsquollturnintoarealhacknotjustsomethinglazyyoudidonenightwhenyouweretired

CreateBasicTemplatesYoucanbreakyourflaskapplicationbutdidyounoticethatldquoHelloWorldrdquoisnrsquotaverygoodHTMLpageThisisawebapplicationandassuchitneedsaproperHTMLresponseTodothatyouwillcreateasimpletemplatethatsaysldquoHelloWorldrdquoinabiggreenfontThefirststepistocreateatemplatesindexhtmlfilethatlookslikethisClickheretoviewcodeimage

indexhtml

lthtmlgt

ltheadgt

lttitlegtGothonsOfPlanetPercal25lttitlegt

ltheadgt

ltbodygt

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

ltbodygt

lthtmlgtIfyouknowwhatHTMListhenthisshouldlookfairly

familiarIfnotresearchHTMLandtrywritingafewwebpagesby

handsoyouknowhowitworksThisHTMLfilehoweverisa

templatewhichmeansthatflaskwillfillinldquoholesrdquointhetext

dependingonvariablesyoupassintothetemplateEveryplaceyou

see$greetingwillbeavariableyoursquollpasstothetemplatethat

altersitscontents

TomakeyourapppydothisyouneedtoaddsomecodetotellflaskwheretoloadthetemplateandtorenderitTakethatfileandchangeitlikethisClickheretoviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3

4app=Flask(__name__)

5

6approute()

7defindex()

8greeting=HelloWorld

9returnrender_template(indexhtmlgreeting=greeting)

10

11if__name__==__main__

12apprun()Paycloseattentiontothenewrendervariable

andhowIchangedthelastlineofindexGETsoitreturns

renderindex()passinginyourgreetingvariable

OnceyouhavethatinplacereloadthewebpageinyourbrowserandyoushouldseeadifferentmessageingreenYoushouldalsobeabletodoaViewSourceonthepageinyourbrowsertoseethatitisvalidHTMLThismayhaveflownbyyouveryfastsoletmeexplainhowatemplateworks1Inyourapppyyoursquoveimportedanewfunctionnamedrender_templateatthetop

2Thisrender_templateknowshowtoloadhtmlfilesoutofthetemplatesdirectorybecausethatisthedefaultmagicsettingforaflaskapplication

3Laterinyourcodewhenthebrowserhitsthedefindexinsteadofjustreturningthestringgreetingyoucallrender_templateandpassthegreetingtoitasavariable

4Thisrender_templatemethodthenloadsthetemplatesindexhtmlfile(eventhoughyoudidnrsquotexplicitlysaytemplates)andprocessesit

5InthistemplatesindexhtmlfileyouhavewhatlookslikenormalHTMLbutthentherersquosldquocoderdquoplacedbetweentwokindsofmarkersOneiswhichmarkspiecesofldquoexecutablecoderdquo(if-statementsfor-loopsetc)TheotheriswhichmarksvariablestobeconvertedintotextandplacedintotheHTMLoutputTheexecutablecodedoesnrsquotshowupintheHTMLTolearnmoreaboutthistemplatelanguagereadtheJinja2documentation

TogetdeeperintothischangethegreetingvariableandtheHTMLtoseewhateffectithasAlsocreateanothertemplatenamedtemplatesfoohtmlandrenderthatlikebefore

StudyDrills1Readthedocumentationathttpflaskpocooorgdocs012whichisthesameastheflaskproject

2Experimentwitheverythingyoucanfindthereincludingtheirexamplecode

3ReadaboutHTML5andCSS3andmakesomeotherhtmlandcssfilesforpractice

4IfyouhaveafriendwhoknowsDjangoandiswillingtohelpyouthenconsiderdoingExercises5051and52inDjangoinsteadtoseewhatthatrsquoslike

CommonStudentQuestionsIcanrsquotseemtoconnecttohttplocalhost5000Tryhttp1270015000instead

WhatisthedifferencebetweeflaskandwebpyNodifferenceIsimplyldquolockedrdquowebpyataparticularversionsothatitwouldbeconsistentforstudentsthennameditflaskLaterversionsofwebpymightbedifferentfromthisversion

Icanrsquotfindindexhtml(orjustaboutanything)YouprobablyaredoingcdbinfirstandthentryingtoworkwiththeprojectDonotdothisAllofthecommandsandinstructionsassumeyouareonedirectoryabovebinsoifyoucanrsquottypepython36apppythenyouareinthewrongdirectory

Whydoweassigngreeting=greetingwhenwecallthetemplateYouarenotassigningtogreetingYouaresettinganamedparametertogivetothetemplateItrsquossortofanassignmentbutitonlyaffectsthecalltothetemplatefunction

Icanrsquotuseport5000onmycomputerYouprobablyhaveananti-virusprograminstalledthatisusingthatportTryadifferentport

AfterinstallingflaskIgetImportErrorNomodulenamedwebYoumostlikelyhavemultipleversionsofpythoninstalledandareusingthewrongoneoryoudidnrsquotdotheinstall

correctlybecauseofanoldversionofpipTryuninstallingflaskandreinstallingitIfthatdoesnrsquotworkmaketriplesureyoursquoreusingtherightversionofpython

Exercise51GettingInputfromaBrowser

WhileitrsquosexcitingtoseethebrowserdisplayldquoHelloWorldrdquoitrsquosevenmoreexcitingtolettheusersubmittexttoyourapplicationfromaformInthisexercisewersquollimproveourstarterwebapplicationbyusingformsandstoringinformationaboutusersintotheirldquosessionsrdquo

HowtheWebWorksTimeforsomeboringstuffYouneedtounderstandabitmoreabouthowthewebworksbeforeyoucanmakeaformThisdescriptionisnrsquotcompletebutitrsquosaccurateandwillhelpyoufigureoutwhatmightbegoingwrongwithyourapplicationAlsocreatingformswillbeeasierifyouknowwhattheydoIrsquollstartwithasimplediagramthatshowsyouthedifferentpartsofawebrequestandhowtheinformationflows

IrsquovelabeledthelineswithletterssoIcanwalkyouthrougharegularrequestprocess1Youtypeintheurlhttptestcomintoyourbrowseranditsendstherequestonline(A)toyourcomputerrsquosnetworkinterface

2Yourrequestgoesoutovertheinternetonline(B)andthentotheremotecomputeronline(C)wheremyserveracceptstherequest

3Oncemycomputeracceptsitmywebapplicationgetsitonline(D)andmyPythoncoderunstheindexGEThandler

4TheresponsecomesoutofmyPythonserverwhenIreturnitandit

goesbacktoyourbrowseroverline(D)again5Theserverrunningthissitetakestheresponseoffline(D)thensendsitbackovertheinternetonline(C)

6Theresponsefromtheserverthencomesofftheinternetonline(B)andyourcomputerrsquosnetworkinterfacehandsittoyourbrowseronline(A)

7FinallyyourbrowserthendisplaystheresponseInthisdescriptionthereareafewtermsyoushouldknowsothatyouhaveacommonvocabularytoworkwithwhentalkingaboutyourwebapplicationBrowserThesoftwarethatyoursquoreprobablyusingeverydayMostpeopledonrsquotknowwhatabrowserreallydoesTheyjustcallbrowsersldquotheinternetrdquoItsjobistotakeaddresses(likehttptestcom)youtypeintotheURLbarthenusethatinformationtomakerequeststotheserveratthataddress

AddressThisisnormallyaURL(UniformResourceLocator)likehttptestcomandindicateswhereabrowsershouldgoThefirstparthttpindicatestheprotocolyouwanttouseinthiscaseldquoHyper-TextTransportProtocolrdquoYoucanalsotryftpibiblioorgtoseehowldquoFileTransportProtocolrdquoworksThehttptestcompartistheldquohostnamerdquoahumanreadableaddressyoucanrememberandwhichmapstoanumbercalledanIPaddresssimilartoatelephonenumberforacomputerontheinternetFinallyURLscanhaveatrailingpathlikethebookpartofhttptestcombookwhichindicatesafileorsomeresourceontheservertoretrievewitharequestTherearemanyotherpartsbutthosearethemainones

ConnectionOnceabrowserknowswhatprotocolyouwanttouse(http)whatserveryouwanttotalkto(httptestcom)andwhatresourceonthatservertogetitmustmakeaconnectionThebrowsersimplyasksyouroperatingsystem(OS)toopenaldquoportrdquotothecomputerusuallyport80WhenitworkstheOShandsbacktoyourprogramsomethingthatworkslikeafilebutisactuallysendingandreceivingbytesoverthenetworkwiresbetweenyourcomputerandtheothercomputerathttptestcomThisisalsothesamethingthathappenswithhttplocalhost8080butinthiscaseyoursquoretellingthebrowsertoconnecttoyourowncomputer(localhost)anduseport8080ratherthanthedefaultof80Youcouldalsodohttptestcom80andgetthesameresultexceptyoursquoreexplicitlysayingtouseport80insteadoflettingitbethatbydefault

RequestYourbrowserisconnectedusingtheaddressyougaveNowitneedstoaskfortheresourceitwants(oryouwant)ontheremoteserverIfyougavebookattheendoftheURLthenyouwantthefile(resource)atbookandmostserverswillusetherealfilebookindexhtmlbutpretenditdoesnrsquotexistWhatthebrowserdoestogetthisresourceissendarequesttotheserverIwonrsquotgetintoexactlyhowitdoesthisbutjustunderstandthatithastosendsomethingtoquerytheserverfortherequestTheinterestingthingisthattheseldquoresourcesrdquodonrsquothavetobefilesForinstancewhenthebrowserinyourapplicationasksforsomethingtheserverisreturningsomethingyourPythoncodegenerated

ServerTheserveristhecomputerattheendofabrowserrsquosconnectionthatknowshowtoansweryourbrowserrsquosrequestsforfilesresourcesMostwebserversjustsendfilesandthatrsquosactuallythemajorityoftrafficButyoursquoreactuallybuildingaserverinPythonthatknowshowtotakerequestsforresourcesandthenreturnstringsthatyoucraftusingPythonWhenyoudothiscraftingyouarepretendingtobeafiletothebrowserbutreallyitrsquosjustcodeAsyoucanseefromExercise50italsodoesnrsquottakemuchcodetocreatearesponse

ResponseThisistheHTML(CSSJavaScriptorimages)yourserverwantstosendbacktothebrowserastheanswertothebrowserrsquosrequestInthecaseoffilesitjustreadsthemoffthediskandsendsthemtothebrowserbutitwrapsthecontentsofthediskinaspecialldquoheaderrdquosothebrowserknowswhatitrsquosgettingInthecaseofyourapplicationyoursquorestillsendingthesamethingincludingtheheaderbutyougeneratethatdataontheflywithyourPythoncode

ThatisthefastestcrashcourseinhowawebbrowseraccessesinformationonserversontheinternetItshouldworkwellenoughforyoutounderstandthisexercisebutifnotreadaboutitasmuchasyoucanuntilyougetitAreallygoodwaytodothatistotakethediagramandbreakdifferentpartsofthewebapplicationyoudidinExercise50Ifyoucanbreakyourwebapplicationinpredictablewaysusingthediagramyoursquollstarttounderstandhowitworks

HowFormsWorkThebestwaytoplaywithformsistowritesomecodethatacceptsformdataandthenseewhatyoucandoTakeyourapppyfileandmakeitlooklikethis

Clickheretoviewcodeimage

form_testpy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hello)

8defindex()

9name=requestargsget(nameNobody)

10

11ifname

12greeting=fHelloname

13else

14greeting=HelloWorld

15

16returnrender_template(indexhtmlgreeting=greeting)

17

18if__name__==__main__

19apprun()Restartit(hitCTRL-Candthenrunitagain)to

makesureitloadsagainthenwithyourbrowsergoto

httplocalhost5000hellowhichshoulddisplayldquoIjustwantedto

sayHelloNobodyrdquoNextchangetheURLinyourbrowserto

httplocalhost5000helloname=Frankandyoursquollseeitsay

ldquoHelloFrankrdquoFinallychangethename=Frankparttobeyourname

Nowitrsquossayinghellotoyou

LetrsquosbreakdownthechangesImadetoyourscript1InsteadofjustastringforgreetingIrsquomnowusingrequestargstogetdatafromthebrowserThisisasimpledictthatcontainstheformvaluesaskey=valuepairs

2Ithenconstructthegreetingfromthenewnamewhichshouldbeveryfamiliartoyoubynow

3EverythingelseaboutthefileisthesameasbeforeYoursquorealsonotrestrictedtojustoneparameterontheURLChangethisexampletogivetwovariableslikethishttplocalhost5000helloname=Frankampgreet=HolaThenchangethecodetogetnameandgreetlikethisClickheretoviewcodeimage

greet=requestargsget(greetHello)

greeting=fgreetname

greeting=fgreetname

YoushouldalsotrynotgivingthegreetandnameparametersontheURLYoursquollsimplysendyourbrowsertohttplocalhost5000hellotoseethattheindexnowdefaultstoldquoNobodyrdquofornameandldquoHellordquoforgreet

CreatingHTMLFormsPassingtheparametersontheURLworksbutitrsquoskindofuglyandnoteasytouseforregularpeopleWhatyoureallywantisaldquoPOSTformrdquowhichisaspecialHTMLfilethathasaltformgttaginitThisformwillcollectinformationfromtheuserthensendittoyourwebapplicationjustlikeyoudidaboveLetrsquosmakeaquickonesoyoucanseehowitworksHerersquosthenewHTMLfileyouneedtocreateintemplateshello_formhtmlClickheretoviewcodeimage

hello_formhtml

lthtmlgt

ltheadgt

lttitlegtSampleWebFormlttitlegt

ltheadgt

ltbodygt

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

ltbodygt

lthtmlgtYoushouldthenchangeapppytolooklikethisClickhere

toviewcodeimage

apppy

1fromflaskimportFlask

2fromflaskimportrender_template

3fromflaskimportrequest

4

5app=Flask(__name__)

6

7approute(hellomethods=[POSTGET])

8defindex()

9greeting=HelloWorld

10

11ifrequestmethod==POST

12name=requestform[name]

13greet=requestform[greet]

14greeting=fgreetname

15returnrender_template(indexhtmlgreeting=greeting)

16else

17returnrender_template(hello_formhtml)

18

19

20if__name__==__main__

21apprun()Onceyoursquovegotthosewrittenupsimplyrestart

thewebapplicationagainandhititwithyourbrowserlikebefore

ThistimeyoursquollgetaformaskingyouforldquoAGreetingrdquoandldquoYourNamerdquoWhenyouhittheSubmitbuttonontheformitwillgiveyouthesamegreetingyounormallygetbutthistimelookattheURLinyourbrowserSeehowitrsquoshttplocalhost5000helloeventhoughyousentinparametersThepartofthehello_formhtmlfilethatmakesthisworkisthelinewithltformaction=hellomethod=POSTgtThistellsyourbrowserto1Collectdatafromtheuserusingtheformfieldsinsidetheform

2SendthemtotheserverusingaPOSTtypeofrequestwhichisjustanotherbrowserrequestthatldquohidesrdquotheformfields

3SendthattothehelloURL(asshownintheaction=hellopart)

YoucanthenseehowthetwoltinputgttagsmatchthenamesofthevariablesinyournewcodeAlsonoticethatinsteadofjustaGETmethodinsideclassindexIhaveanothermethodPOSTHowthisnewapplicationworksisasfollows1Yourrequestgoestoindex()likenormalexceptnowthereisanif-statementthatcheckstherequestmethodforeitherPOSTorGETmethodsThisishowthebrowsertellsapppythatarequestiseitheraformsubmissionorURLparameters

2IfrequestmethodisPOSTthenyouprocesstheformasifitwerefilledoutandsubmittedreturningthepropergreeting

3Ifrequestmethodisanythingelsethenyousimplyreturnthehello_formhtmlfortheusertofillout

AsanexercisegointothetemplatesindexhtmlfileandaddalinkbacktojusthellosothatyoucankeepfillingouttheformandseeingtheresultsMakesureyoucanexplainhowthislinkworksandhowitrsquoslettingyoucyclebetweentemplatesindexhtmlandtemplateshello_formhtmlandwhatrsquosbeingruninsidethislatestPythoncode

CreatingaLayoutTemplateWhenyouworkonyourgameinthenextexerciseyoursquollneedtomakeabunchoflittleHTMLpagesWritingafullwebpageeachtimewillquicklybecometediousLuckilyyoucancreatealdquolayoutrdquotemplateorakindofshellthatwillwrapallyourotherpageswithcommonheadersandfootersGoodprogrammerstrytoreducerepetitionsolayoutsareessentialforbeingagoodprogrammerChangetemplatesindexhtmltobelikethisClickheretoviewcodeimage

index_laid_outhtml

extendslayouthtml

blockcontent

ifgreeting

Ijustwantedtosay

ltemstyle=colorgreenfont-size2emgtgreetingltemgt

else

ltemgtHelloltemgtworld

endif

endblock

Thenchangetemplateshello_formhtmltobelikethisClickheretoviewcodeimage

hello_form_laid_outhtml

extendslayouthtml

blockcontent

lth1gtFillOutThisFormlth1gt

ltformaction=hellomethod=POSTgt

AGreetingltinputtype=textname=greetgt

ltbrgt

YourNameltinputtype=textname=namegt

ltbrgt

ltinputtype=submitgt

ltformgt

endblock

AllwersquoredoingisstrippingouttheldquoboilerplaterdquoatthetopandthebottomwhichisalwaysoneverypageWersquollputthatbackintoasingletemplateslayouthtmlfilethathandlesitforusfromnowonOnceyouhavethosechangescreateatemplateslayouthtmlfilewiththisinitClickheretoviewcodeimage

layouthtml

lthtmlgt

ltheadgt

lttitlegtGothonsFromPlanetPercal25lttitlegt

ltheadgt

ltbodygt

blockcontent

endblock

ltbodygt

lthtmlgtThisfilelookslikearegulartemplateexceptthatitrsquos

goingtobepassedthecontentsoftheothertemplatesandusedto

wrapthemAnythingyouputinheredoesnrsquotneedtobeintheother

templatesYourotherHTMLtemplateswillbeinsertedintothe

blockcontentsectionflaskknowstousethislayouthtmlasthe

layoutbecauseyouputextendslayouthtmlatthetopofyour

templates

WritingAutomatedTestsforFormsItrsquoseasytotestawebapplicationwithyourbrowserbyjusthittingrefreshbutcomeonwersquoreprogrammershereWhydosomerepetitivetaskwhenwecanwritesomecodetotestourapplicationWhatyoursquoregoingtodonextiswritealittletestforyourwebapplicationformbasedonwhatyoulearnedinExercise

47IfyoudonrsquotrememberExercise47readitagainCreateanewfilenamedtestsapp_testspywiththisClickheretoviewcodeimage

app_testspy

1fromnosetoolsimport

2fromappimportapp

3

4appconfig[TESTING]=True

5web=apptest_client()

6

7deftest_index()

8rv=webget(follow_redirects=True)

9assert_equal(rvstatus_code404)

10

11rv=webget(hellofollow_redirects=True)

12assert_equal(rvstatus_code200)

13assert_in(bFillOutThisFormrvdata)

14

15data=nameZedgreetHola

16rv=webpost(hellofollow_redirects=Truedata=data)

17assert_in(bZedrvdata)

18assert_in(bHolarvdata)Finallyusenoseteststorun

thistestsetupandtestyourwebapplication$nosetests

ndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndashndash

Ran1testin0059s

OK

WhatIrsquomdoinghereisIrsquomactuallyimportingthewholeapplicationfromtheapppymodulethenrunningitmanuallyTheflaskframeworkhasaverysimpleAPIforprocessingrequestswhichlookslikethisClickheretoviewcodeimage

data=nameZedgreetHola

rv=webpost(hellofollow_redirects=Truedata=data)Thismeans

youcansendaPOSTrequestusingthepost()methodandthengiveit

theformdataasadictEverythingelseworksthesameastesting

webget()requests

Inthetestsapp_testspyautomatedtestIrsquomfirstmakingsuretheURLreturnsaldquo404NotFoundrdquoresponsesinceitactuallydoesnrsquotexistThenIrsquomcheckingthathelloworkswithbothaGETandaPOSTformFollowing

thetestshouldbefairlysimpleevenifyoumightnottotallyknowwhatrsquosgoingonTakesometimestudyingthislatestapplicationespeciallyhowtheautomatedtestingworksMakesureyouunderstandhowIimportedtheapplicationfromapppyandranitdirectlyfortheautomatedtestThisisanimportanttrickthatwillleadtomorelearning

StudyDrills1ReadevenmoreaboutHTMLandgivethesimpleformabetterlayoutIthelpstodrawwhatyouwanttodoonpaperandthenimplementitwithHTML

2Thisoneishardbuttrytofigureouthowyoursquoddoafileuploadformsothatyoucanuploadanimageandsaveittothedisk

3Thisisevenmoremind-numbingbutgofindtheHTTPRFC(whichisthedocumentthatdescribeshowHTTPworks)andreadasmuchofitasyoucanItisreallyboringbutcomesinhandyonceinawhile

4ThiswillalsobereallydifficultbutseeifyoucanfindsomeonetohelpyousetupawebserverlikeApacheNginxorthttpdTrytoserveacoupleofyourhtmlandcssfileswithitjusttoseeifyoucanDonrsquotworryifyoucanrsquotWebserverskindofsuck

5Takeabreakafterthisandjusttrymakingasmanydifferentwebapplicationsasyoucan

BreakingItThisisagreatplacetofigureouthowtobreakwebapplicationsYoushouldexperimentwiththefollowing

1HowmuchdamagecanyoudowiththeFLASK_DEBUGsettingonBecarefulthatyoudonrsquotwipeyourselfoutdoingthis

2LetrsquossayyoudonrsquothavedefaultparametersfortheformsWhatcouldgowrong

3YoursquorecheckingforPOSTandthenldquoanythingelserdquoYoucanusethecurlcommandlinetooltogeneratedifferentrequesttypesWhathappens

Exercise52TheStartofYourWebGame

WersquorecomingtotheendofthebookandinthisexerciseIrsquomgoingtoreallychallengeyouWhenyoursquoredoneyoursquollbeareasonablycompetentPythonbeginnerYoursquollstillneedtogothroughafewmorebooksandwriteacouplemoreprojectsbutyoursquollhavetheskillstocompletethemTheonlyobstacleswillbetimemotivationandresourcesInthisexercisewewonrsquotmakeacompletegamebutinsteadwersquollmakeanldquoenginerdquothatcanrunthegamefromExercise47inthebrowserThiswillinvolverefactoringExercise43mixinginthestructurefromExercise47addingautomatedtestsandfinallycreatingawebenginethatcanrunthegamesThisexercisewillbehugeandIpredictyoucouldspendanywherefromaweektomonthsonitbeforemovingonItrsquosbesttoattackitinlittlechunksanddoabitanighttakingyourtimetomakeeverythingworkbeforemovingon

RefactoringtheExercise43GameYoursquovebeenalteringthegothonwebprojectfortwoexercisesandyoursquolldoitonemoretimeinthisexerciseTheskillyoursquorelearningiscalledldquorefactoringrdquoorasIliketocallitldquofixingstuffrdquoRefactoringisatermprogrammersusetodescribetheprocessoftakingoldcodeandchangingittohavenewfeaturesorjusttocleanitupYoursquovebeendoingthiswithoutevenknowingitasitrsquossecondnaturetobuildingsoftwareWhatyoursquolldointhispartistaketheideasfromExercise47ofatestableldquomaprdquoofRoomsandthegamefromExercise43andcombinethemtogethertocreateanewgamestructureItwillhavethesamecontentjustldquorefactoredrdquotohaveabetterstructureThefirststepistograbthecodefromex47gamepycopyittogothonwebplanispherepycopythetestsex47_testspyfiletotestsplanisphere_testspyandrunnosetestsagaintomakesureitkeepsworkingThewordldquoplanisphererdquoisjustasynonymforldquomaprdquowhichavoidsPythonrsquosbuilt-inmapfunctionThethesaurusisyourfriend

WarningFromnowonIwonrsquotshowyoutheoutputofatestrunJustassumethatyoushouldbedoingitanditrsquolllookliketheprecedingunlessyouhaveanerror

OnceyouhavethecodefromExercise47copiedoveritrsquostimetorefactorittohavetheExercise43mapinitIrsquomgoingtostartoffbylayingdownthebasicstructureandthenyoursquollhaveanassignmenttomaketheplanispherepyfileandtheplanisphere_testspyfilecompleteLayoutthebasicstructureofthemapusingtheRoomclassasitisnowClickheretoviewcodeimage

planispherepy

1classRoom(object)

2

3def__init__(selfnamedescription)

4selfname=name5selfdescription=description

6selfpaths=

7

8defgo(selfdirection)

9returnselfpathsget(directionNone)

10

11defadd_paths(selfpaths)

12selfpathsupdate(paths)

13

14

15central_corridor=Room(CentralCorridor

16

17TheGothonsofPlanetPercal25haveinvadedyourshipand

destroyed

18yourentirecrewYouarethelastsurvivingmemberandyour

last

19missionistogettheneutrondestructbombfromtheWeapons

Armoryput

20itinthebridgeandblowtheshipupaftergettingintoan

escapepod

21

22YourerunningdownthecentralcorridortotheWeaponsArmory

whena

23Gothonjumpsoutredscalyskindarkgrimyteethandevil

clown

24costumeflowingaroundhishatefilledbodyHesblocking

thedoorto

25theArmoryandabouttopullaweapontoblastyou

26)

27

28

29laser_weapon_armory=Room(LaserWeaponArmory

30

31LuckyforyoutheymadeyoulearnGothoninsultsinthe

academyYou

32telltheoneGothonjokeyouknowLbhezbgurevffbsngjura

furfvgf

33nebhaqgurubhfrfurfvgfnebhaqgurubhfrTheGothon

stopstries

34nottolaughthenbustsoutlaughingandcantmoveWhile

hes

35laughingyourunupandshoothimsquareintheheadputting

himdown

36thenjumpthroughtheWeaponArmorydoor

37

38YoudoadiverollintotheWeaponArmorycrouchandscanthe

roomfor

39moreGothonsthatmightbehidingItsdeadquiettoo

quietYou

40standupandruntothefarsideoftheroomandfindthe

neutronbomb

41initscontainerTheresakeypadlockontheboxandyou

needthe

42codetogetthebomboutIfyougetthecodewrong10times

thenthe

43lockclosesforeverandyoucantgetthebombThecodeis3

digits

44)

45

46

47the_bridge=Room(TheBridge

48

49Thecontainerclicksopenandthesealbreakslettinggas

outYou

50grabtheneutronbombandrunasfastasyoucantothebridge

whereyou

51mustplaceitintherightspot

52

53YouburstontotheBridgewiththenetrondestructbombunder

yourarm

54andsurprise5Gothonswhoaretryingtotakecontrolofthe

shipEach

55ofthemhasanevenuglierclowncostumethanthelastThey

havent

56pulledtheirweaponsoutyetastheyseetheactivebomb

underyourarm

57anddontwanttosetitoff

58)

59

60

61escape_pod=Room(EscapePod

62

63Youpointyourblasteratthebombunderyourarmandthe

Gothonsput

64theirhandsupandstarttosweatYouinchbackwardtothe

dooropen

65itandthencarefullyplacethebombonthefloorpointing

your

66blasteratitYouthenjumpbackthroughthedoorpunchthe

close

67buttonandblastthelocksotheGothonscantgetoutNow

thatthe

68bombisplacedyouruntotheescapepodtogetoffthistin

can

69

70Yourushthroughtheshipdesperatelytryingtomakeittothe

escape

71podbeforethewholeshipexplodesItseemslikehardlyany

Gothons

72areontheshipsoyourrunisclearofinterferenceYou

gettothe

73chamberwiththeescapepodsandnowneedtopickoneto

takeSomeof

74themcouldbedamagedbutyoudonthavetimeto

lookTheres5pods

75whichonedoyoutake

76)

77

78

79the_end_winner=Room(TheEnd

80

81Youjumpintopod2andhittheejectbuttonThepodeasily

slidesout

82intospaceheadingtotheplanetbelowAsitfliestothe

planetyou

83lookbackandseeyourshipimplodethenexplodelikeabright

star

84takingouttheGothonshipatthesametimeYouwon

85)

86

87

88the_end_loser=Room(TheEnd

89

90YoujumpintoarandompodandhittheejectbuttonThepod

escapes

91outintothevoidofspacethenimplodesasthehull

rupturescrushing

92yourbodyintojamjelly

93

94)

95

96escape_podadd_paths(

972the_end_winner

98the_end_loser

99)

100

101generic_death=Room(deathYoudied)

102

103the_bridgeadd_paths(

104throwthebombgeneric_death

105slowlyplacethebombescape_pod

106)

107

108laser_weapon_armoryadd_paths(

1090132the_bridge

110generic_death

111)

112

113central_corridoradd_paths(

114shootgeneric_death

115dodgegeneric_death

116tellajokelaser_weapon_armory

117)

118

119START=central_corridor

120

121defload_room(name)

122

123Thereisapotentialsecurityproblemhere

124WhogetstosetnameCanthatexposeavariable

125

126returnglobals()get(name)

127

128defname_room(room)

129

130SamepossiblesecurityproblemCanyoutrustroom

131Whatsabettersolutionthanthisglobalslookup

132

133forkeyvalueinglobals()items()

134ifvalue==room

135returnkeyYoursquollnoticethatthereareacouple

ofproblemswithourRoomclassandthismap1Wehavetoputthe

textthatwasintheif-elseclausesthatgotprintedbeforeentering

aroomaspartofeachroomThismeansyoucanrsquotshufflethe

planispherearoundwhichwouldbeniceYoursquollbefixingthatupin

thisexercise

2TherearepartsintheoriginalgamewherewerancodethatdeterminedthingslikethebombrsquoskeypadcodeortherightpodInthisgamewejustpicksomedefaultsandgowithitbutlateryoursquollbegivenStudyDrillstomakethisworkagain

3Irsquovejustmadeageneric_deathendingforallofthebaddecisionswhichyoursquollhavetofinishformeYoursquollneedtogobackthroughandaddinalltheoriginalendingsandmakesuretheywork

4Irsquovegotanewkindoftransitionlabeledthatwillbeusedforaldquocatch-allrdquoactionintheengine

Onceyoursquovegotthatbasicallywrittenoutherersquosthenewautomatedtesttestsplanisphere_testpythatyoushouldhavetogetyourselfstartedClickheretoviewcodeimage

planisphere_testspy

1fromnosetoolsimport

2fromgothonwebplanisphereimport

3

4deftest_room()

5gold=Room(GoldRoom

6Thisroomhasgoldinityoucangrab

Theresa

7doortothenorth)

8assert_equal(goldnameGoldRoom)

9assert_equal(goldpaths)

10

11deftest_room_paths()

12center=Room(CenterTestroominthecenter)

13north=Room(NorthTestroominthenorth)

14south=Room(SouthTestroominthesouth)

15

16centeradd_paths(northnorthsouthsouth)

17assert_equal(centergo(north)north)

18assert_equal(centergo(south)south)

19

20deftest_map()

21start=Room(StartYoucangowestanddownahole)

22west=Room(TreesTherearetreeshereyoucango

east)

23down=Room(DungeonItsdarkdownhereyoucango

up)

24

25startadd_paths(westwestdowndown)

26westadd_paths(eaststart)

27downadd_paths(upstart)

28

29assert_equal(startgo(west)west)

30assert_equal(startgo(west)go(east)start)

31assert_equal(startgo(down)go(up)start)

32

33deftest_gothon_game_map()

34start_room=load_room(START)

35assert_equal(start_roomgo(shoot)generic_death)

36assert_equal(start_roomgo(dodge)generic_death)

37

38room=start_roomgo(tellajoke)

39assert_equal(roomlaser_weapon_armory)Yourtaskinthis

partoftheexerciseistocompletethemapandmaketheautomated

testcompletelyvalidatethewholemapThisincludesfixingallthe

generic_deathobjectstoberealendingsMakesurethisworksreally

wellandthatyourtestisascompleteaspossiblebecausewersquollbe

changingthismaplaterandyoursquollusetheteststomakesureit

keepsworking

CreatinganEngineYoushouldhaveyourgamemapworkingandagoodunittestforitInowwantyoutomakeasimplelittlegameenginethatwillruntheroomscollectinputfromtheplayerandkeeptrackofwhereaplayerisinthegameWersquollbeusingthesessionsyoujustlearnedtomakeasimplegameenginethatwilldothefollowing

1Startanewgamefornewusers2Presenttheroomtotheuser3Takeinputfromtheuser4Runuserinputthroughthegame5Displaytheresultsandkeepgoinguntiltheuserdies

Todothisyoursquoregoingtotakethetrustyapppyyoursquovebeenhackingonandcreateafullyworkingsession-basedgameengineThecatchisIrsquomgoingtomakeaverysimpleonewithbasicHTMLfilesanditrsquollbeuptoyoutocompleteitHerersquosthebaseengineClickheretoviewcodeimage

apppy

1fromflaskimportFlasksessionredirecturl_forescape

request

2fromflaskimportrender_template

3fromgothonwebimportplanisphere

4

5app=Flask(__name__)

6

7approute()

8defindex()

9thisisusedtosetupthesessionwithstartingvalues

10session[room_name]=planisphereSTART

11returnredirect(url_for(game))

12

13approute(gamemethods=[GETPOST])

14defgame()

15room_name=sessionget(room_name)

16

17ifrequestmethod==GET

18ifroom_name

19room=planisphereload_room(room_name)

20returnrender_template(show_roomhtmlroom=room)

21else

22whyisthereheredoyouneedit

23returnrender_template(you_diedhtml)

24else

25action=requestformget(action)

26

27ifroom_nameandaction

28room=planisphereload_room(room_name)

29next_room=roomgo(action)

30

31ifnotnext_room

32session[room_name]=

planispherename_room(room)

33else

34session[room_name]=

planispherename_room(next_room)

35

36returnredirect(url_for(game))

37

38

39YOUSHOULDCHANGETHISIFYOUPUTONTHEINTERNET

40appsecret_key=A0Zr98j3yXR~XHHjmN]LWXRT

41

42if__name__==__main__

43apprun()Thereareevenmorenewthingsinthisscript

butamazinglyitrsquosanentireweb-basedgameengineinasmallfile

BeforeyourunapppyyouneedtochangeyourPYTHONPATHenvironment

variableDonrsquotknowwhatthatisIknowitrsquoskindofdumbbutyou

havetolearnwhatthisistorunevenbasicPythonprogramsthatrsquos

howPythonpeoplelikethings

InyourTerminaltypeClickheretoviewcodeimageexportPYTHONPATH=$PYTHONPATH

OnWindowsPowerShelldoClickheretoviewcodeimage$envPYTHONPATH=$envPYTHONPATH

$envPYTHONPATH=$envPYTHONPATH

YoushouldonlyhavetodoitoncepershellsessionbutifyougetanimporterrorthenyouprobablyneedtodothisoryoudiditwrongYoushouldnextdeletetemplateshello_formhtmlandtemplatesindexhtmlandcreatethetwotemplatesmentionedintheprecedingcodeHerersquosaverysimpletemplatesshow_roomhtmlClickheretoviewcodeimage

show_roomhtml

extendslayouthtml

blockcontent

lth1gtroomnamelth1gt

ltpregt

roomdescription

ltpregt

ifroomnamein[deathTheEnd]

ltpgtltahref=gtPlayAgainltagtltpgt

else

ltpgt

ltformaction=gamemethod=POSTgt

-ltinputtype=textname=actiongtltinputtype=SUBMITgt

ltformgt

ltpgt

endif

endblock

ThatisthetemplatetoshowaroomasyoutravelthroughthegameNextyouneedonetotellsomeonetheydiedinthecasethattheygottotheendofthemaponaccidentwhichistemplatesyou_diedhtmlClickheretoviewcodeimage

you_diedhtml

lth1gtYouDiedlth1gt

ltpgtLookslikeyoubitthedustltpgt

ltpgtltahref=gtPlayAgainltagtltpgtWiththoseinplaceyoushouldnow

beabletodothefollowing1Getthetesttestsapp_testspy

workingagainsothatyouaretestingthegameYouwonrsquotbeableto

domuchmorethanafewclicksinthegamebecauseofsessionsbut

youshouldbeabletodosomebasics

2Runthepython36apppyscriptandtestoutthegameYoushouldbeabletorefreshandfixthegamelikenormalYoushouldalsobeabletoworkwiththegameHTMLandengineuntilitdoesallthethingsyouwantittodo

YourFinalExamDoyoufeellikethiswasahugeamountofinformationthrownatyouallatonceGoodIwantyoutohavesomethingtotinkerwithwhileyoubuildyourskillsTocompletethisexerciseIrsquomgoingtogiveyouafinalsetoftasksforyoutocompleteonyourownYoursquollnoticethatwhatyoursquovewrittensofarisnrsquotverywellbuiltitisjustafirstversionofthecodeYourjobnowistomakethegamemorecompletebydoingthesethings

1FixallthebugsImentioninthecodeandanythatIdidnrsquotmentionIfyoufindnewbugsletmeknow

2Improvealloftheautomatedtestssothatyoutestmoreoftheapplicationandgettoapointwhereyouuseatestratherthanyourbrowsertochecktheapplicationwhileyouwork

3MaketheHTMLlookbetter4Researchloginsandcreateasignupsystemfortheapplicationsopeoplecanhaveloginsandhighscores

5Completethegamemapmakingitaslargeandfeature-completeaspossible

6Givepeoplealdquohelprdquosystemthatletsthemaskwhattheycandoateachroominthegame

7Addanyotherfeaturesyoucanthinkoftothegame8CreateseveralldquomapsrdquoandletpeoplechooseagametheywanttorunYourapppyengineshouldbeabletorunanymapofroomsyougiveitsoyoucansupportmultiplegames

9FinallyusewhatyoulearnedinExercises48and49tocreateabetterinputprocessorYouhavemostofthecodenecessaryyoujustneedtoimprovethegrammarandhookituptoyourinputformandtheGameEngine

Goodluck

Goodluck

CommonStudentQuestionsIrsquomusingsessionsinmygameandIcanrsquottestitwithnosetestsReadtheFlaskTestingDocumentationaboutldquoOtherTestingTricksrdquo(httpflaskpocooorgdocs012testingother-testing-tricks)forinformationoncreatingfakesessionsinsideyourtests

IgetanImportErrorItcouldbeoneormoreofthesewrongdirectorywrongPythonversionPYTHONPATHnotsetno__init__pyfileandorspellingmistakeinimport

NextSteps

YoursquorenotaprogrammerquiteyetIliketothinkofthisbookasgivingyouyourldquoprogrammingblackbeltrdquoYouknowenoughtostartanotherbookonprogrammingandhandleitjustfineThisbookshouldhavegivenyouthementaltoolsandattitudeyouneedtogothroughmostPythonbooksandactuallylearnsomethingItmightevenmakeiteasyIrecommendyoucheckoutsomeoftheseprojectsandtrytobuildsomethingwiththem

bullLearnRubyTheHardWay(httpslearnrubythehardwayorg)YouwilllearnevenmoreaboutprogrammingasyoulearnmoreprogramminglanguagessotrylearningRubytoo

bullTheDjangoTutorial(httpsdocsdjangoprojectcomen111intro)BuildawebapplicationwiththeDjangowebframework

bullSciPy(httpswwwscipyorg)Checkthisoutifyoursquoreintosciencemathandengineering

bullPyGame(httpwwwpygameorg)MakeagamewithgraphicsandsoundbullPandas(httppandaspydataorg)Usethisfordoingdatamanipulationandanalysis

bullNaturalLanguageToolkit(httpwwwnltkorg)Usethisforanalyzingwrittentextandwritingthingslikespamfiltersandchatbots

bullTensorFlow(httpswwwtensorfloworg)Usethisformachinelearningandvisualization

bullRequests(httpdocspython-requestsorg)LearntheclientsideofHTTPandtheweb

bullScraPy(httpsscrapyorg)Tryscrapingsomewebsitestogetinformationoffthem

bullKivy(httpskivyorg)Createuserinterfacesondesktopsandmobileplatforms

bullLearnCTheHardWay(httpslearncodethehardwayorg)AfteryoursquorefamiliarwithPythontrylearningCandalgorithmswithmyotherbookTakeitslowCisdifferentbutaverygoodthingtolearn

PickoneoftheprecedingresourcesandgothroughanytutorialsanddocumentationtheyhaveAsyougothroughdocumentationwithcodeinittype

inallofthecodeandmakeitworkThatrsquoshowIdoitThatrsquoshoweveryprogrammerdoesitReadingprogrammingdocumentationisnotenoughtolearnityouhavetodoitAfteryougetthroughthetutorialandanyotherdocumentationtheyhavemakesomethingAnythingwilldoevensomethingsomeoneelsehasalreadywrittenJustmakesomethingJustunderstandanythingyouwritewillprobablysuckThatrsquosalrightthoughIsuckateveryprogramminglanguageatfirstNobodywritespureperfectgoldwhentheyrsquoreabeginnerandanyonewhotellsyoutheydidisahugeliar

HowtoLearnAnyProgrammingLanguageIrsquomgoingtoteachyouhowtolearnmostoftheprogramminglanguagesyoumaywanttolearninthefutureTheorganizationofthisbookisbasedonhowIandmanyotherprogrammerslearnnewlanguagesTheprocessthatIusuallyfollowisasfollows

1Getabookorsomeintroductorytextaboutthelanguage2Gothroughthebookandtypeinallofthecodemakingallofitrun3Readthebookasyouworkonthecodetakingnotes4Usethelanguagetoimplementasmallsetofprogramsyouarefamiliarwithinanotherlanguage

5ReadotherpeoplersquoscodeinthelanguageandtrytocopytheirpatternsInthisbookIforcedyoutogothroughthisprocessveryslowlyandinsmallchunksOtherbooksarenrsquotorganizedthesamewayandthismeansyouhavetoextrapolatehowIrsquovemadeyoudothistohowtheircontentisorganizedThebestwaytodothisistoreadthebooklightlyandmakealistofallthemajorcodesectionsTurnthislistintoasetofexercisesbasedonthechaptersandthensimplydotheminorderoneatatimeTheprecedingprocessalsoworksfornewtechnologiesassumingtheyhavebooksyoucanreadForanythingwithoutbooksyoudotheaboveprocessbutuseonlinedocumentationorsourcecodeasyourinitialintroductionEachnewlanguageyoulearnmakesyouabetterprogrammerandasyoulearnmorelanguagestheybecomeeasiertolearnByyourthirdorfourthlanguageyoushouldbeabletopickupsimilarlanguagesinaweekwithstrangerlanguagestakinglongerNowthatyouknowPythonyoucouldpotentiallylearnRubyandJavaScriptfairlyquicklybycomparisonThisissimplybecausemanylanguagessharesimilarconceptsandonceyoulearntheconceptsinonelanguagetheyworkinothersThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbea

ThefinalthingtorememberaboutlearninganewlanguageisthisDonrsquotbeastupidtouristAstupidtouristissomeonewhogoestoanothercountryandthencomplainsthatthefoodisnrsquotlikethefoodathome(ldquoWhycanrsquotIgetagoodburgerinthisstupidcountryrdquo)WhenyoursquorelearninganewlanguageassumethatwhatitdoesisnrsquotstupiditrsquosjustdifferentandembraceitsoyoucanlearnitAfteryoulearnalanguagethoughdonrsquotbeaslavetothatlanguagersquoswayofdoingthingsSometimesthepeoplewhousealanguageactuallydosomeveryidioticthingsfornootherreasonthanldquothatrsquoshowwersquovealwaysdoneitrdquoIfyoulikeyourstylebetterandyouknowhoweveryoneelsedoesitthenfeelfreetobreaktheirrulesifitimprovesthingsIreallyenjoylearningnewprogramminglanguagesIthinkofmyselfasaldquoprogrammeranthropologistrdquoandthinkoflanguagesaslittleinsightsaboutthegroupofprogrammerswhousethemIrsquomlearningalanguagetheyallusetotalktoeachotherthroughcomputersandIfindthisfascinatingThenagainIrsquomkindofaweirdguysojustlearnprogramminglanguagesbecauseyouwanttoEnjoyThisisreallyfunstuff

AdvicefromanOldProgrammer

YoursquovefinishedthisbookandhavedecidedtocontinuewithprogrammingMaybeitwillbeacareerforyouormaybeitwillbeahobbyYoursquollneedsomeadvicetomakesureyoucontinueontherightpathandgetthemostenjoymentoutofyournewlychosenactivityIrsquovebeenprogrammingforaverylongtimeSolongthatitrsquosincrediblyboringtomeAtthetimethatIwrotethisbookIknewabout20programminglanguagesandcouldlearnnewonesinaboutadaytoaweekdependingonhowweirdtheywereEventuallythoughthisjustbecameboringandcouldnrsquotholdmyinterestanymoreThisdoesnrsquotmeanIthinkprogrammingisboringorthatyouwillthinkitrsquosboringonlythatIfindituninterestingatthispointinmyjourneyWhatIdiscoveredafterthisjourneyoflearningisthatitrsquosnotthelanguagesthatmatterbutwhatyoudowiththemActuallyIalwaysknewthatbutIrsquodgetdistractedbythelanguagesandforgetitperiodicallyNowIneverforgetitandneithershouldyouWhichprogramminglanguageyoulearnandusedoesnrsquotmatterDonotgetsuckedintothereligionsurroundingprogramminglanguagesasthatwillonlyblindyoutotheirtruepurposeofbeingyourtoolfordoinginterestingthingsProgrammingasanintellectualactivityistheonlyartformthatallowsyoutocreateinteractiveartYoucancreateprojectsthatotherpeoplecanplaywithandyoucantalktothemindirectlyNootherartformisquitethisinteractiveMoviesflowtotheaudienceinonedirectionPaintingsdonotmoveCodegoesbothwaysProgrammingasaprofessionisonlymoderatelyinterestingItcanbeagoodjobbutyoucouldmakeaboutthesamemoneyandbehappierrunningafastfoodjointYoursquoremuchbetteroffusingcodeasyoursecretweaponinanotherprofessionPeoplewhocancodeintheworldoftechnologycompaniesareadimeadozenandgetnorespectPeoplewhocancodeinbiologymedicinegovernmentsociologyphysicshistoryandmathematicsarerespectedandcandoamazingthingstoadvancethosedisciplinesOfcourseallofthisadviceispointlessIfyoulikedlearningtowritesoftwarewiththisbookyoushouldtrytouseittoimproveyourlifeanywayyoucanGooutandexplorethisweirdwonderfulnewintellectualpursuitthatbarelyanyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhile

anyoneinthelast50yearshasbeenabletoexploreMightaswellenjoyitwhileyoucanFinallyIrsquollsaythatlearningtocreatesoftwarechangesyouandmakesyoudifferentNotbetterorworsejustdifferentYoumayfindthatpeopletreatyouharshlybecauseyoucancreatesoftwaremaybeusingwordslikeldquonerdrdquoMaybeyoursquollfindthatbecauseyoucandissecttheirlogictheyhatearguingwithyouYoumayevenfindthatsimplyknowinghowacomputerworksmakesyouannoyingandweirdtothemTothisIhavejustonepieceofadvicetheycangotohellTheworldneedsmoreweirdpeoplewhoknowhowthingsworkandwholovetofigureitalloutWhentheytreatyoulikethisjustrememberthatthisisyourjourneynottheirsBeingdifferentisnotacrimeandpeoplewhotellyouitisarejustjealousthatyoursquovepickedupaskilltheyneverintheirwildestdreamscouldacquireYoucancodeTheycannotThatisprettydamncool

AppendixCommandLineCrashCourse

ThisappendixisasuperfastcourseinusingthecommandlineItisintendedtobedonerapidlyinaboutadayortwoandnotmeanttoteachyouadvancedshellusage

IntroductionShutUpandShellThisappendixisacrashcourseinusingthecommandlinetomakeyourcomputerperformtasksAsacrashcourseitrsquosnotasdetailedorextensiveasmyotherbooksItissimplydesignedtogetyoubarelycapableenoughtostartusingyourcomputerlikearealprogrammerdoesWhenyoursquoredonewiththisappendixyouwillbeabletogivemostofthebasiccommandsthateveryshellusertoucheseverydayYoursquollunderstandthebasicsofdirectoriesandafewotherconceptsTheonlypieceofadviceIamgoingtogiveyouisthis

ShutupandtypeallofthisinSorrytobemeanbutthatrsquoswhatyouhavetodoIfyouhaveanirrationalfearofthecommandlinetheonlywaytoconqueranirrationalfearistojustshutupandfightthroughitYouarenotgoingtodestroyyourcomputerYouarenotgoingtobethrownintosomejailatthebottomofMicrosoftrsquosRedmondcampusYourfriendswonrsquotlaughatyouforbeinganerdSimplyignoreanystupidweirdreasonsyouhaveforfearingthecommandlineWhyBecauseifyouwanttolearntocodethenyoumustlearnthisProgramminglanguagesareadvancedwaystocontrolyourcomputerwithlanguageThecommandlineisthebabybrotherofprogramminglanguagesLearningthecommandlineteachesyoutocontrolthecomputerusinglanguageOnceyougetpastthatyoucanthenmoveontowritingcodeandfeelinglikeyouactuallyownthehunkofmetalyoujustbought

HowtoUseThisAppendixThebestwaytousethisappendixistodothefollowing

bullGetyourselfasmallpapernotebookandapenbullStartatthebeginningoftheappendixanddoeachexerciseexactlyasyoursquoretold

bullWhenyoureadsomethingthatdoesnrsquotmakesenseorthatyoudonrsquotunderstandwriteitdowninyournotebookLeavealittlespacesoyoucanwriteananswer

bullAfteryoufinishanexercisegobackthroughyournotebookandreviewthequestionsyouhaveTrytoanswerthembysearchingonlineandaskingfriendswhomightknowtheanswerEmailmeathelplearncodethehardwayorgandIrsquollhelpyoutoo

JustkeepgoingthroughthisprocessofdoinganexercisewritingdownquestionsyouhavethengoingbackthroughandansweringthequestionsyoucanBythetimeyoursquoredoneyoursquollactuallyknowalotmorethanyouthinkaboutusingthecommandline

YouWillBeMemorizingThingsIrsquomwarningyouaheadoftimethatIrsquomgoingtomakeyoumemorizethingsrightawayThisisthequickestwaytogetyoucapableatsomethingbutforsomepeoplememorizationispainfulJustfightthroughitanddoitanywayMemorizationisanimportantskillinlearningthingssoyoushouldgetoveryourfearofitHerersquoshowyoumemorizethings

bullTellyourselfyouwilldoitDonrsquottrytofindtricksoreasywaysoutofitjustsitdownanddoit

bullWritewhatyouwanttomemorizeonsomeindexcardsPutonehalfofwhatyouneedtolearnononesidethenanotherhalfontheotherside

bullEverydayforabout15to30minutesdrillyourselfontheindexcardstryingtorecalleachonePutanycardsyoudonrsquotgetrightintoadifferentpilejustdrillthosecardsuntilyougetboredthentrythewholedeckandseeifyouimprove

bullBeforeyougotobeddrilljustthecardsyougotwrongforabout5minutesthengotosleep

ThereareothertechniqueslikeyoucanwritewhatyouneedtolearnonasheetofpaperlaminateitthenstickittothewallofyourshowerWhileyoursquorebathingdrilltheknowledgewithoutlookingandwhenyougetstuckglanceatittorefreshyourmemoryIfyoudothiseverydayyoushouldbeabletomemorizemostthingsItellyoutomemorizeinaboutaweektoamonthOnceyoudonearlyeverythingelsebecomeseasierandintuitivewhichisthepurposeofmemorizationItrsquosnottoteachyouabstractconceptsbutrathertoingrainthebasicssothattheyareintuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthese

intuitiveandyoudonrsquothavetothinkaboutthemOnceyoursquovememorizedthesebasicstheystopbeingspeedbumpspreventingyoufromlearningmoreadvancedabstractconcepts

TheSetupInthisappendixyouwillbeinstructedtodothreethings

bullDosomethingsinyourshell(commandlineTerminalPowerShell)bullLearnaboutwhatyoujustdidbullDomoreonyourown

ForthisfirstexerciseyoursquollbeexpectedtogetyourTerminalopenandworkingsothatyoucandotherestoftheappendix

DoThisGetyourTerminalshellorPowerShellworkingsoyoucanaccessitquicklyandknowthatitworksmacOS

FormacOSyoursquollneedtodothisbullHolddownthecommandkeyandhitthespacebarbullAsearchbarwillpopupbullTypeTerminalbullClickontheTerminalapplicationthatlookskindoflikeablackboxbullThiswillopenTerminalbullYoucannowgotoyourdockandCTRL-clicktopullupthemenuthenselectOptionsrarrKeepIndock

NowyouhaveyourTerminalopenanditrsquosinyourdocksoyoucangettoitLinux

IrsquomassumingthatifyouhaveLinuxthenyoualreadyknowhowtogetatyourTerminalLookthroughthemenuforyourwindowmanagerforanythingnamedldquoShellrdquoorldquoTerminalrdquoWindows

OnWindowswersquoregoingtousePowerShellPeopleusedtoworkwithaprogramcalledcmdexebutitrsquosnotnearlyasusableasPowerShellIfyouhaveWindows7orlaterdothis

bullClickStartbullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquo

bullInldquoSearchprogramsandfilesrdquotypeldquopowershellrdquobullHitEnter

IfyoudonrsquothaveWindows7youshouldseriouslyconsiderupgradingIfyoustillinsistonnotupgradingthenyoucantryinstallingPowerShellfromMicrosoftrsquosdownloadcenterSearchonlinetofindldquopowershelldownloadsrdquoforyourversionofWindowsYouareonyourownthoughsinceIdonrsquothaveWindowsXPbuthopefullythePowerShellexperienceisthesame

YouLearnedThisYoulearnedhowtogetyourTerminalopensoyoucandotherestofthisappendix

WarningIfyouhavethatreallysmartfriendwhoalreadyknowsLinuxignoreherwhenshetellsyoutousesomethingotherthanBashIrsquomteachingyouBashThatrsquositShewillclaimthatzshwillgiveyou30moreIQpointsandwinyoumillionsinthestockmarketIgnoreherYourgoalistogetcapableenoughandatthislevelitdoesnrsquotmatterwhichshellyouuseThenextwarningisstayoffIRCorotherplaceswhereldquohackersrdquohangoutTheythinkitrsquosfunnytohandyoucommandsthatcandestroyyourcomputerThecommandrm-rfisaclassicthatyoumustnevertypeJustavoidthemIfyouneedhelpmakesureyougetitfromsomeoneyoutrustandnotfromrandomidiotsontheinternet

DoMoreThisexercisehasalargeldquodomorerdquopartTheotherexercisesarenotasinvolvedasthisonebutIrsquomhavingyouprimeyourbrainfortherestoftheappendixbydoingsomememorizationJusttrustmethiswillmakethingssilkysmoothlateronLinuxmacOS

TakethislistofcommandsandcreateindexcardswiththenamesontheleftononesideandthedefinitionsontheothersideDrillthemeverydaywhilecontinuingwiththelessonsinthisappendix

pwdprintworkingdirectoryhostnamemycomputerrsquosnetworkname

mkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectorymvmoveafileordirectorylesspagethroughafilecatprintthewholefilexargsexecuteargumentsfindfindfilesgrepfindthingsinsidefilesmanreadamanualpageaproposfindwhichmanualpageisappropriateenvlookatyourenvironmentechoprintsomeargumentsexportexportsetanewenvironmentvariableexitexittheshellsudoDANGERbecomesuperuserrootDANGER

Windows

IfyoursquoreusingWindowsthenherersquosyourlistofcommandspwdprintworkingdirectoryhostnamemycomputerrsquosnetworknamemkdirmakedirectorycdchangedirectorylslistdirectoryrmdirremovedirectorypushdpushdirectorypopdpopdirectorycpcopyafileordirectory

robocopyrobustcopymvmoveafileordirectorymorepagethroughafiletypeprintthewholefileforfilesrunacommandonlotsoffilesdir-rfindfilesselect-stringfindthingsinsidefileshelpreadamanualpagehelpctrfindwhatmanualpageisappropriateechoprintsomeargumentssetexportsetanewenvironmentvariableexitexittheshellrunasDANGERbecomesuperuserrootDANGER

DrilldrilldrillDrilluntilyoucansaythesephrasesrightawaywhenyouseethatwordThendrilltheinversesothatyoureadthephraseandknowwhatcommandwilldothatYoursquorebuildingyourvocabularybydoingthisbutdonrsquotspendsomuchtimeyougonutsandgetbored

PathsFoldersDirectories(pwd)Inthisexerciseyoulearnhowtoprintyourworkingdirectorywiththepwdcommand

DoThisIrsquomgoingtoteachyouhowtoreadtheseldquosessionsrdquothatIshowyouYoudonrsquothavetotypeeverythingIlistherejustsomeoftheparts

bullYoudonottypeinthe$(Unix)orlt(Windows)ThatrsquosjustmeshowingyoumysessionsoyoucanseewhatIgot

bullYoutypeinthestuffafter$orltthenhitEnterSoifIhave$pwdyoutypejustpwdandhitEnter

bullYoucanthenseewhatIhaveforoutputfollowedbyanother$orltpromptThatcontentistheoutputandyoushouldseethesameoutput

LetrsquosdoasimplefirstcommandsoyoucangetthehangofthisLinuxmacOS

Exercise2Session

$pwd

Userszedshaw

$

Windows

Exercise2WindowsSession

PSCUserszedgtpwd

Path

----

CUserszed

PSCUserszedlt

WarningInthisappendixIneedtosavespacesothatyoucanfocusontheimportantdetailsofthecommandsTodothisIrsquomgoingtostripoutthefirstpartoftheprompt(thePSCUserszedabove)andleavejustthelittlegtpartThismeansyourpromptwonrsquotlookexactlythesamebutdonrsquotworryaboutthatRememberthatfromnowonIrsquollonlyhavethegttotellyouthatrsquosthepromptIrsquomdoingthesamethingfortheUnixpromptsbutUnixpromptsaresovariedthatmostpeoplegetusedto$meaningldquojustthepromptrdquo

YouLearnedThisYourpromptwilllookdifferentfrommineYoumayhaveyourusernamebeforethe$andthenameofyourcomputerOnWindowsitwillprobablylookdifferenttooThekeyisthatyouseethefollowingpattern

bullTherersquosapromptbullYoutypeacommandthereInthiscaseitrsquospwdbullItprintedsomethingbullRepeat

Youjustlearnedwhatpwddoeswhichmeansldquoprintworkingdirectoryrdquo

WhatrsquosadirectoryItrsquosafolderFolderanddirectoryarethesamethingandtheyrsquoreusedinterchangeablyWhenyouopenyourfilebrowseronyourcomputertographicallyfindfilesyouarewalkingthroughfoldersThosefoldersaretheexactsamethingsastheseldquodirectoriesrdquowersquoregoingtoworkwith

DoMorebullTypepwd20timesandeachtimesayldquoprintworkingdirectoryrdquobullWritedownthepaththatthiscommandgivesyouFinditwithyourgraphicalfilebrowserofchoice

bullNoseriouslytypeit20timesandsayitoutloudSsshJustdoit

IfYouGetLostAsyougothroughtheseinstructionsyoumaygetlostYoumaynotknowwhereyouareorwhereafileisandhavenoideahowtocontinueTosolvethisproblemIamgoingtoteachyouthecommandstotypetostopbeinglostWheneveryougetlostitismostlikelybecauseyouweretypingcommandsandhavenoideawhereyoursquoveendedupWhatyoushoulddoistypepwdtoprintyourcurrentdirectoryThistellsyouwhereyouareThenextthingisyouneedtohaveawayofgettingbacktowhereyouaresafeyourhomeTodothistypecd~andyouarebackinyourhomeThismeansifyougetlostatanytimetype

pwd

cd~

ThefirstcommandpwdtellsyouwhereyouareThesecondcommandcd~takesyouhomesoyoucantryagain

DoThisRightnowfigureoutwhereyouareandthengohomeusingpwdandcd~Thiswillmakesureyouarealwaysintherightplace

YouLearnedThisHowtogetbacktoyourhomeifyouevergetlost

MakeaDirectory(mkdir)Inthisexerciseyoulearnhowtomakeanewdirectory(folder)usingthemkdircommand

DoThis

DoThisRememberYouneedtogohomefirstDoyourpwdthencd~beforedoingthisexerciseBeforeyoudoallexercisesinthisappendixalwaysgohomefirstLinuxmacOS

Clickheretoviewcodeimage

Exercise4Session

$pwd

$cd~

$mkdirtemp

$mkdirtempstuff

$mkdirtempstuffthings

$mkdir-ptempstuffthingsorangeapplepeargrape

$

Windows

Clickheretoviewcodeimage

Exercise4WindowsSession

gtpwd

gtcd~

gtmkdirtemp

DirectoryCUserszed

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMtemp

gtmkdirtempstuff

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011902AMstuff

gtmkdirtempstuffthings

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtmkdirtempstuffthingsorangeapplepeargrape

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gt

ThisistheonlytimeIrsquolllistthepwdandcd~commandsTheyareexpectedintheexerciseseverytimeDothemallthetime

YouLearnedThisNowwegetintotypingmorethanonecommandTheseareallthedifferentwaysyoucanrunmkdirWhatdoesmkdirdoItmakesdirectoriesWhyareyouaskingthatYoushouldbedoingyourindexcardsandgettingyourcommandsmemorizedIfyoudonrsquotknowthatldquomkdirmakesdirectoriesrdquothenkeepworkingtheindexcardsWhatdoesitmeantomakeadirectoryYoumightcalldirectoriesldquofoldersrdquoTheyrsquorethesamethingAllyoudidaboveiscreatedirectoriesinsidedirectoriesinsideofmoredirectoriesThisiscalledaldquopathrdquoanditrsquosawayofsayingldquofirsttempthenstuffthenthingsandthatrsquoswhereIwantitrdquoItrsquosasetofdirectionstothecomputerofwhereyouwanttoputsomethinginthetreeoffolders(directories)thatmakeupyourcomputerrsquosharddisk

WarningInthisappendixIrsquomusingthe(slash)characterforallpathssincetheyworkthesameonallcomputersnowHoweverWindowsuserswillneedtoknowthatyoucanalsousethe(backslash)characterandotherWindowsuserswilltypicallyexpectthatattimes

DoMorebullTheconceptofaldquopathrdquomightconfuseyouatthispointDonrsquotworryWersquolldoalotmorewiththemandthenyoursquollgetit

bullMake20otherdirectoriesinsidethetempdirectoryinvariouslevelsGolookatthemwithagraphicalfilebrowser

bullMakeadirectorywithaspaceinthenamebyputtingquotesarounditmkdirIHaveFun

bullIfthetempdirectoryalreadyexiststhenyoursquollgetanerrorUsecdtochangetoaworkdirectorythatyoucancontrolandtryitthereOnWindowsDesktopisagoodplace

ChangeDirectory(cd)Inthisexerciseyoulearnhowtochangefromonedirectorytoanotherusingthecdcommand

DoThisIrsquomgoingtogiveyoutheinstructionsforthesesessionsonemoretime

bullYoudonottypeinthe$(Unix)orgt(Windows)bullYoutypeinthestuffafterthisthenhitEnterIfIhave$cdtempyoujusttypecdtempandhitEnter

bullTheoutputcomesafteryouhitEnterfollowedbyanother$orgtpromptbullAlwaysgohomefirstDopwdandthencd~soyougobacktoyourstartingpoint

LinuxmacOS

Clickheretoviewcodeimage

Exercise5Session

$cdtemp

$pwd

~temp

$cdstuff

$pwd

~tempstuff

$cdthings

$pwd

~tempstuffthings

$cdorange

$pwd

~tempstuffthingsorange

$cdapple

$pwd

~tempstuffthingsorangeapple

$cdpear

$pwd

~tempstuffthingsorangeapplepear

$cdgrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$cd

$pwd

~tempstuffthingsorangeapple

$cd

$cd

$pwd

~tempstuffthings

$cd

$pwd

~

$cdtempstuffthingsorangeapplepeargrape

$pwd

~tempstuffthingsorangeapplepeargrape

$cd

$pwd

~

$

Windows

Clickheretoviewcodeimage

Exercise5WindowsSession

gtcdtemp

gtpwd

Path

----

CUserszedtemp

gtcdstuff

gtpwd

Path

----

CUserszedtempstuff

gtcdthings

gtpwd

Path

----

CUserszedtempstuffthings

gtcdorange

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcdapple

gtpwd

Path

----

CUserszedtempstuffthingsorangeapple

gtcdpear

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepear

gtcdgrape

gtpwd

Path

----

CUserszedtempstuffthingsorangeapplepeargrape

gtcd

gtcd

gtcd

gtpwd

Path

----

CUserszedtempstuffthingsorange

gtcd

gtpwd

Path

----

CUserszedtempstuff

gtcd

gtcd

gtcdtempstuffthingsorangeapplepeargrape

gtcd

gtpwd

Path

----

CUserszed

gt

YouLearnedThisYoumadeallthesedirectoriesinthelastexerciseandnowyoursquorejustmovingaroundinsidethemwiththecdcommandInmysessionaboveIalsousepwdtocheckwhereIamsoremembernottotypetheoutputthatpwdprintsForexampleonline3yousee~tempbutthatrsquostheoutputofpwdfromthepromptaboveitDonottypethisinYoushouldalsoseehowIusethetomoveldquouprdquointhetreeandpath

DoMoreAveryimportantpartoflearningtousethecommandlineinterface(CLI)onacomputerwithagraphicaluserinterface(GUI)isfiguringouthowtheyworktogetherWhenIstartedusingcomputerstherewasnoGUIandyoudideverythingwiththeDOSprompt(theCLI)LaterwhencomputersbecamepowerfulenoughthateveryonecouldhavegraphicsitwassimpleformetomatchCLIdirectorieswithGUIwindowsandfoldersMostpeopletodayhoweverhavenocomprehensionoftheCLIpathsanddirectoriesInfactitrsquosverydifficulttoteachittothemandtheonlywaytolearnabouttheconnectionisforyoutoconstantlyworkwiththeCLIuntilonedayitclicksthatthingsyoudointheGUIwillshowupintheCLI

dayitclicksthatthingsyoudointheGUIwillshowupintheCLIThewayyoudothisisbyspendingsometimefindingdirectorieswithyourGUIfilebrowserthengoingtothemwithyourCLIThisiswhatyoursquolldonext

bullcdtotheappledirectorywithonecommandbullcdbacktotempwithonecommandbutnotfurtherabovethatbullFindouthowtocdtoyourldquohomedirectoryrdquowithonecommandbullcdtoyourDocumentsdirectorythenfinditwithyourGUIfilebrowser(FinderWindowsExploreretc)

bullcdtoyourDownloadsdirectorythenfinditwithyourfilebrowserbullFindanotherdirectorywithyourfilebrowserthencdtoitbullRememberwhenyouputquotesaroundadirectorywithspacesinitYoucandothatwithanycommandForexampleifyouhaveadirectoryIHaveFunthenyoucandocdIHaveFun

ListDirectory(ls)Inthisexerciseyoulearnhowtolistthecontentsofadirectorywiththelscommand

DoThisBeforeyoustartmakesureyoucdbacktothedirectoryabovetempIfyouhavenoideawhereyouareusepwdtofigureitoutandthenmovethereLinuxmacOS

Exercise6Session

$cdtemp

$ls

stuff

$cdstuff

$ls

things

$cdthings

$ls

orange

$cdorange

$ls

apple

$cdapple

$ls

pear

$cdpear

$ls

$cdgrape

$ls

$cd

$ls

grape

$cd

$ls

orange

$cd

$ls

stuff

$

Windows

Clickheretoviewcodeimage

Exercise6WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuff

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcdthings

gtls

DirectoryCUserszedtempstuffthings

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMorange

gtcdorange

gtls

DirectoryCUserszedtempstuffthingsorange

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMapple

gtcdapple

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcdpear

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcdgrape

gtls

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapplepear

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMgrape

gtcd

gtls

DirectoryCUserszedtempstuffthingsorangeapple

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMpear

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gt

YouLearnedThisThelscommandlistsoutthecontentsofthedirectoryyouarecurrentlyinYoucanseemeusecdtochangeintodifferentdirectoriesandthenlistwhatrsquosinthemsoIknowwhichdirectorytogotonextTherearealotofoptionsforthelscommandbutyoursquolllearnhowtogethelponthoselaterwhenwecoverthehelpcommand

DoMore

bullTypeeveryoneofthesecommandsinYouhavetoactuallytypethesetolearnthemJustreadingthemisnotgoodenoughIrsquollstopyellingnow

bullOnUnixtrythels-lRcommandwhileyoursquoreintempbullOnWindowsdothesamethingwithdir-RbullUsecdtogettootherdirectoriesonyourcomputerandthenuselstoseewhatrsquosinthem

bullUpdateyournotebookwithnewquestionsIknowyouprobablyhavesomebecauseIrsquomnotcoveringeverythingaboutthiscommand

bullRememberthatifyougetlostuselsandpwdtofigureoutwhereyouareandthengotowhereyouneedtobewithcd

RemoveDirectory(rmdir)Inthisexerciseyoulearnhowtoremoveanemptydirectory

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise7Session

$cdtemp

$ls

stuff

$cdstuffthingsorangeapplepeargrape

$cd

$rmdirgrape

$cd

$rmdirpear

$cd

$ls

apple

$rmdirapple

$cd

$ls

orange

$rmdirorange

$cd

$ls

things

$rmdirthings

$cd

$ls

stuff

$rmdirstuff

$pwd

~temp

$

WarningIfyoutrytodormdironmacOSanditrefusestoremovethedirectoryeventhoughyouarepositiveitrsquosemptythenthereisactuallyafileintherecalledDS_StoreInthatcasetyperm-rfltdirgtinstead(replaceltdirgtwiththedirectoryname)

Windows

Clickheretoviewcodeimage

Exercise7WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011903AMstuff

gtcdstuffthingsorangeapplepeargrape

gtcd

gtrmdirgrape

gtcd

gtrmdirpear

gtcd

gtrmdirapple

gtcd

gtrmdirorange

gtcd

gtls

DirectoryCUserszedtempstuff

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMthings

gtrmdirthings

gtcd

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12172011914AMstuff

gtrmdirstuff

gtpwd

Path

----

CUserszedtemp

gtcd

gt

YouLearnedThisIrsquomnowmixingupthecommandssomakesureyoutypethemexactlyandpayattentionEverytimeyoumakeamistakeitrsquosbecauseyouarenrsquotpayingattentionIfyoufindyourselfmakingmanymistakesthentakeabreakorjustquitforthedayYoursquovealwaysgottomorrowtotryagainInthisexampleyoursquolllearnhowtoremoveadirectoryItrsquoseasyYoujustgotothedirectoryrightaboveitthentypermdirltdirgtreplacingltdirgtwiththenameofthedirectorytoremove

DoMorebullMake20moredirectoriesandremovethemallbullMakeasinglepathofdirectoriesthatis10deepandremovethemoneatatimejustlikeIdidpreviously

bullIfyoutrytoremoveadirectorywithcontentsyouwillgetanerrorIrsquollshowyouhowtoremovethoseinlaterexercises

MovingAround(pushdpopd)InthisexerciseyoulearnhowtosaveyourcurrentlocationandgotoanewlocationwithpushdYouthenlearnhowtoreturntothesavedlocationwithpopd

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise8Session

$cdtemp

$mkdirilikeicecream

$pushdilikeicecream

~tempilikeicecream~temp

$popd

~temp

$pwd

~temp

$pushdilike

tempiliketemp

$pwd

~tempilike

$pushdicecream

~tempilikeicecreamtempiliketemp

$pwd

~tempilikeicecream

$popd

tempiliketemp

$pwd

~tempilike

$popd

~temp

$pushdilikeicecream

~tempilikeicecream~temp

$pushd

~temp~tempilikeicecream

$pwd

~temp

$pushd

~tempilikeicecream~temp

$pwd

~tempilikeicecream

$

Windows

Windows

Clickheretoviewcodeimage

Exercise8WindowsSession

gtcdtemp

gtmkdirilikeicecream

DirectoryCUserszedtempilike

ModeLastWriteTimeLengthName

---------------------------

d----122020111105AMicecream

gtpushdilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtemp

gtpushdilike

gtpwd

Path

----

CUserszedtempilike

gtpushdicecream

gtpwd

Path

----

CUserszedtempilikeicecream

gtpopd

gtpwd

Path

----

CUserszedtempilike

gtpopd

gt

WarningInWindowsyounormallydonrsquotneedthe-poptionlikeyoudoinLinuxHoweverIbelievethisisamorerecentdevelopmentsoyoumayrunintoolderWindowsPowerShellversionsthatdorequirethe-pIfyouhavemoreinformationonthispleaseemailmeathelplearncodethehardwayorgsoIcansortoutwhethertomention-pforWindowsornot

YouLearnedThisYoursquoregettingintoprogrammerterritorywiththesecommandsbuttheyrsquoresohandyIhavetoteachthemtoyouThesecommandsletyoutemporarilygotoadifferentdirectoryandthencomebackeasilyswitchingbetweenthetwoThepushdcommandtakesyourcurrentdirectoryandldquopushesrdquoitintoalistforlaterthenitchangestoanotherdirectoryItrsquoslikesayingldquoSavewhereIamthengohererdquoThepopdcommandtakesthelastdirectoryyoupushedandldquopopsrdquoitofftakingyoubackthereFinallyonUnixpushdifyourunitbyitselfwithnoargumentsitwillswitchbetweenyourcurrentdirectoryandthelastoneyoupushedItrsquosaneasywaytoswitchbetweentwodirectoriesThisdoesnotworkinPowerShell

DoMorebullUsethesecommandstomovearounddirectoriesalloveryourcomputerbullRemovetheilikeicecreamdirectoriesandmakeyourownthenmovearoundinthem

bullExplaintoyourselftheoutputthatpushdandpopdwillprintoutforyouNoticehowitworkslikeastack

bullYoualreadyknowthisbutrememberthatmkdir-p(onLinuxmacOS)willmakeanentirepathevenifallthedirectoriesdonrsquotexistThatrsquoswhatIdidfirstforthisexercise

bullRememberthatWindowswillmakeafullpathanddoesnotneedthe-p

MakingEmptyFiles(touchNew-Item)Inthisexerciseyoulearnhowtomakeanemptyfileusingthetouch(New-ItemonWindows)command

DoThisLinuxmacOS

Exercise9Session

$cdtemp

$touchiamcooltxt

$ls

iamcooltxt

$

Windows

Clickheretoviewcodeimage

Exercise9WindowsSession

gtcdtemp

gtNew-Itemiamcooltxt-typefile

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12172011903AMiamcooltxt

gt

YouLearnedThisYoulearnedhowtomakeanemptyfileOnUnixtouchdoesthisanditalsochangesthetimesonthefileIrarelyuseitforanythingotherthanmakingemptyfilesOnWindowsyoudonrsquothavethiscommandsoyoulearnedhowtousetheNew-Itemcommandwhichdoesthesamethingbutcanalsomakenewdirectories

DoMorebullUnixMakeadirectorychangetoitandthenmakeafileinitThenchangeonelevelupandrunthermdircommandinthisdirectoryYoushouldgetanerrorTrytounderstandwhyyougotthiserror

bullWindowsDothesamethingbutyouwonrsquotgetanerrorYoursquollgetapromptaskingifyoureallywanttoremovethedirectory

CopyaFile(cp)Inthisexerciseyoulearnhowtocopyafilefromonelocationtoanotherwiththecpcommand

DoThisLinuxmacOS

Clickheretoviewcodeimage

Exercise10Session

$cdtemp

$cpiamcooltxtneattxt

$ls

iamcooltxtneattxt

$cpneattxtawesometxt

$ls

awesometxtiamcooltxtneattxt

$cpawesometxtthefourthfiletxt

$ls

awesometxtiamcooltxtneattxtthefourthfiletxt

$mkdirsomething

$cpawesometxtsomething

$ls

awesometxtiamcooltxtneattxtsomethingthefourthfiletxt

$lssomething

awesometxt

$cp-rsomethingnewplace

$lsnewplace

awesometxt

$

Windows

Clickheretoviewcodeimage

Exercise10WindowsSession

gtcdtemp

gtcpiamcooltxtneattxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpneattxtawesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

gtcpawesometxtthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtmkdirsomething

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

gtcpawesometxtsomething

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMsomething

-a---12222011449PM0awesometxt

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtlssomething

DirectoryCUserszedtempsomething

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtcp-recursesomethingnewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gt

YouLearnedThisNowyoucancopyfilesItrsquossimpletojusttakeafileandcopyittoanewoneInthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectory

InthisexerciseIalsomakeanewdirectoryandcopyafileintothatdirectoryIrsquomgoingtotellyouasecretaboutprogrammersandsystemadministratorsnowTheyarelazyIrsquomlazyMyfriendsarelazyThatrsquoswhyweusecomputersWeliketomakecomputersdoboringthingsforusIntheexercisessofaryouhavebeentypingrepetitiveboringcommandssothatyoucanlearnthembutusuallyitrsquosnotlikethisUsuallyifyoufindyourselfdoingsomethingboringandrepetitivetherersquosprobablyaprogrammerwhohasfiguredouthowtomakeiteasierYoujustdonrsquotknowaboutityetTheotherthingaboutprogrammersistheyarenrsquotnearlyascleverasyouthinkIfyouoverthinkwhattotypethenyoursquollprobablygetitwrongInsteadtrytoimaginewhatthenameofacommandistoyouandtryitChancesarethatitrsquosanameorsomeabbreviationsimilartowhatyouthoughtitwasIfyoustillcanrsquotfigureitoutintuitivelythenaskaroundandsearchonlineHopefullyitrsquosnotsomethingreallystupidlikeROBOCOPY

DoMorebullUsethecp-rcommandtocopymoredirectorieswithfilesinthembullCopyafiletoyourhomedirectoryordesktopbullFindthesefilesinyourGUIandopentheminatexteditorbullNoticehowsometimesIputa(slash)attheendofadirectoryThatmakessurethefileisreallyadirectorysoifthedirectorydoesnrsquotexistIrsquollgetanerror

MovingaFile(mv)Inthisexerciseyoulearnhowtomoveafilefromonelocationtoanotherusingthemvcommand

DoThisLinuxmacOS

Exercise11Session

$cdtemp

$mvawesometxtuncooltxt

$ls

newplaceuncooltxt

$mvnewplaceoldplace

$ls

oldplaceuncooltxt

$mvoldplacenewplace

$ls

newplaceuncooltxt

$

Windows

Clickheretoviewcodeimage

Exercise11WindowsSession

gtcdtemp

gtmvawesometxtuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvnewplaceoldplace

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMoldplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtmvoldplacenewplace

gtlsnewplace

DirectoryCUserszedtempnewplace

ModeLastWriteTimeLengthName

---------------------------

-a---12222011449PM0awesometxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gt

YouLearnedThisMovingfilesorratherrenamingthemItrsquoseasygivetheoldnameandthenewname

DoMoreMoveafileinthenewplacedirectorytoanotherdirectorythenmoveitback

ViewaFile(lessmore)TodothisexerciseyoursquoregoingtodosomeworkusingthecommandsyouknowsofarYoursquollalsoneedatexteditorthatcanmakeplaintext(txt)filesHerersquoswhatyoudo

bullOpenyourtexteditorandtypesomestuffintoanewfileOnmacOSthiscouldbeTextWranglerOnWindowsthismightbeNotepad++OnLinuxthiscouldbegeditAnyeditorwillwork

bullSavethatfiletoyourdesktopandnameittesttxtbullInyourshellusethecommandsyouknowtocopythisfiletoyourtempdirectorythatyoursquovebeenworkingwith

Onceyoursquovedonethatcompletethisexercise

Onceyoursquovedonethatcompletethisexercise

DoThisLinuxmacOS

Exercise12Session

$lesstesttxt

[displaysfilehere]

$

ThatrsquositTogetoutoflessjusttypeq(asinquit)Windows

Exercise12WindowsSession

gtmoretesttxt

[displaysfilehere]

gt

WarningIntheprecedingoutputIrsquomshowing[displaysfilehere]toldquoabbreviaterdquowhatthatprogramshowsIrsquolldothiswhenImeantosayldquoShowingyoutheoutputofthisprogramistoocomplexsojustinsertwhatyouseeonyourcomputerhereandpretendIdidshowittoyourdquoYourscreenwillnotactuallyshowthis

YouLearnedThisThisisonewaytolookatthecontentsofafileItrsquosusefulbecauseifthefilehasmanylinesitwillldquopagerdquosothatonlyonescreenfulatatimeisvisibleIntheDoMoresectionyoursquollplaywiththissomemore

DoMorebullOpenyourtextfileagainandrepeatedlycopy-pastethetextsothatitrsquosabout50ndash100lineslong

bullCopyittoyourtempdirectoryagainsoyoucanlookatitbullNowdotheexerciseagainbutthistimepagethroughitOnUnixyouuse

thespacebarandw(theletterw)togodownandupArrowkeysalsoworkOnWindowsjusthitthespacebartopagethrough

bullLookatsomeoftheemptyfilesyoucreatedtoobullThecpcommandwilloverwritefilesthatalreadyexistsobecarefulcopyingfilesaround

StreamaFile(cat)YoursquoregoingtodosomemoresetupforthisonesoyougetusedtomakingfilesinoneprogramandthenaccessingthemfromthecommandlineWiththesametexteditorfromthelastexercisecreateanotherfilenamedtest2txtbutthistimesaveitdirectlytoyourtempdirectory

DoThisLinuxmacOS

Exercise13Session

$lesstest2txt

[displaysfilehere]

$cattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

$cattesttxt

Hitherethisiscool

$

Windows

Exercise13WindowsSession

gtmoretest2txt

[displaysfilehere]

gtcattest2txt

Iamafunguy

Dontyouknowwhy

BecauseImakepoems

thatmakebabiescry

gtcattesttxt

Hitherethisiscool

gt

RememberthatwhenIsay[displaysfilehere]IrsquomabbreviatingtheoutputofthatcommandsoIdonrsquothavetoshowyouexactlyeverything

YouLearnedThisDoyoulikemypoemTotallygoingtowinaNobelAnywayyoualreadyknowthefirstcommandandIrsquomjusthavingyoucheckthatyourfileisthereThenyoucatthefiletothescreenThiscommandjustspewsthewholefiletothescreenwithnopagingorstoppingTodemonstratethatIhaveyoudothistotesttxtwhichshouldjustspewabunchoflinesfromthatexercise

DoMorebullMakeafewmoretextfilesandworkwithcatbullUnixTrycattesttxttest2txtandseewhatitdoesbullWindowsTrycattesttxttest2txtandseewhatitdoes

RemovingaFile(rm)Inthisexerciseyoulearnhowtoremove(delete)afileusingthermcommand

DoThisLinux

Clickheretoviewcodeimage

Exercise14Session

$cdtemp

$ls

uncooltxtiamcooltxtneattxtsomethingthefourthfiletxt

$rmuncooltxt

$ls

iamcooltxtneattxtsomethingthefourthfiletxt

$rmiamcooltxtneattxtthefourthfiletxt

$ls

something

$cp-rsomethingnewplace

$

$rmsomethingawesometxt

$rmdirsomething

$rm-rfnewplace

$ls

$

Windows

Clickheretoviewcodeimage

Exercise14WindowsSession

gtcdtemp

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

-a---12222011449PM0uncooltxt

gtrmuncooltxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

-a---12222011449PM0iamcooltxt

-a---12222011449PM0neattxt

-a---12222011449PM0thefourthfiletxt

gtrmiamcooltxt

gtrmneattxt

gtrmthefourthfiletxt

gtls

DirectoryCUserszedtemp

ModeLastWriteTimeLengthName

---------------------------

d----12222011452PMnewplace

d----12222011452PMsomething

gtcp-rsomethingnewplace

gtrmsomethingawesometxt

gtrmdirsomething

gtrm-rnewplace

gtls

gt

YouLearnedThisHerewecleanupthefilesfromthelastexerciseRememberwhenIhadyoutrytormdironadirectorywithsomethinginitWellthatfailedbecauseyoucanrsquotremoveadirectorywithfilesinitTodothatyouhavetoremovethefileorrecursivelydeleteallofitscontentsThatrsquoswhatyoudidattheendofthis

DoMorebullCleanupeverythingintempfromalltheexercisessofarbullWriteinyournotebooktobecarefulwhenrunningrecursiveremoveonfiles

ExitingYourTerminal(exit)DoThisLinuxmacOS

Exercise23Session

$exit

Windows

Exercise23WindowsSession

gtexit

YouLearnedThisYourfinalexerciseishowtoexitaTerminalAgainthisisveryeasybutIrsquomgoingtohaveyoudomore

DoMore

ForyourlastsetofexercisesIrsquomgoingtohaveyouusethehelpsystemtolookupasetofcommandsyoushouldresearchandlearnhowtouseonyourownHerersquosthelistforUnix

bullxargsbullsudobullchmodbullchown

ForWindowslookupthesethingsbullforfilesbullrunasbullattribbullicacls

Findoutwhattheseareplaywiththemandthenaddthemtoyourindexcards

CommandLineNextStepsYouhavecompletedthecrashcourseAtthispointyoushouldbeabarelycapableshelluserTherersquosawholehugelistoftricksandkeysequencesyoudonrsquotknowyetandIrsquomgoingtogiveyouafewfinalplacestogoresearchmore

UnixBashReferencesTheshellyoursquovebeenusingiscalledBashItrsquosnotthegreatestshellbutitrsquoseverywhereandhasalotoffeaturessoitrsquosagoodstartHerersquosashortlistoflinksaboutBashyoushouldgoread

BashCheatSheethttpslearncodethehardwayorgunixbash_cheat_sheetpdf(createdbyRaphaelandCClicensed)

ReferenceManualhttpwwwgnuorgsoftwarebashmanualbashrefhtml

PowerShellReferencesOnWindowstherersquosreallyonlyPowerShellHerersquosalistofusefullinksforyourelatedtoPowerShell

OwnerrsquosManualhttptechnetmicrosoftcomen-uslibraryee221100aspx

CheatSheethttpsdownloadmicrosoftcomdownload2122122F0B9-0EE6-4E6D-BFD6-F9DCD27C07F9WS12_QuickRef_Download_FilesPowerShell_LangRef_v3pdf

MasterPowerShellhttppowershellcomcsblogsebookdefaultaspx

Index

Symbols(colon)creatingfunctions61ndash62(dot)operator146ndash148193(double-quotes)avoidusingwithTrueFalse31createstrings26ndash27createstringswithsingle-quotesvs29escapinginsidestrings34ndash36promptandpass47

gt=(greater-than-equal)operator16ndash1797+=(incrementby)operator69ndash70105lt=(less-than-equal)operator16ndash1797-(minus)operator16ndash17=(notequal)operator97ndash98100ndash102(single-quotes)createstrings26ndash27createstringswithdouble-quotesvs29escapinginsidestrings34ndash36indicatingstrings57

(triple-single-quotes)36(triple-quotes)dedentfunction170ndash175errorswhenputtingspacesbetween33escapinginsidestrings3436

(slash)character16ndash17257(backslash)character33ndash34257(doublebacklash)character36_(underscore)character20ndash2162189+(plus)operator16ndash1754==(equal)operatorfunctionof21

practicingBooleanlogic100ndash102intruthtables98astruthterm97

=(single-equal)operator21(poundoroctothorpe)character1214ndash1517(percent)operator1617ndash18(asterisk)operator16ndash17[]leftandrightbracketslists112ndash114^(caret)characterviewoutput11charactersembeddedvariablesinstrings24ndash25lt(lessthan)operator16ndash17ltgt=(notequal)vs102gt(greaterthan)operator16ndash1791

AactivatescriptPowershell195Addressesweb225altered()functioninheritance180ndash183Alternativetexteditors6ndash7and

inBooleanlogic100ndash102astruthterm96ndash98

apppy

buildfirstwebsite217ndash221creategameengine239ndash241createHTMLforms228ndash229howformswork226ndash227writeautomatedtestsforforms231ndash232

app_testspyfile231241aproposcommand252args60ndash62Argumentscreatingfunctions6266argv

asargumentvariable42

promptingandpassingusing46ndash47readingandwritingfiles54readingfiles48ndash50unpacking42ndash44usinginput()vs44

Arrayslistsvs114ASCII(AmericanStandardCodeforInformationInterchange)80ndash81assert_equal()functionautomatedtesting201ndash203assert_raises()functionwritingtestexpectedtofail215asterisk()operator16ndash17Atomtexteditoralternativesto6ndash7Linuxsetup4ndash5macOSsetup2Windowssetup3ndash4workingwithfirstprogram9

Automatedtestsforforms232improving242overviewof200ndash203refactoringgothonwebgameusing238ndash239testfirstwith206ndash207

BBackslash()character33ndash34257Bashreferences283Big5encoding85bindirectoryskeletonprojectdirectory198Bits8182Blocksofcode106ndash110Booleanlogicmemorizingvslearning98practicing100ndash102rulesforif-statements126

Bottomupprocessesvstopdown169Brackets([])lists112ndash114Branchesandfunctions122ndash124Breakingfiles8592232Browsercreateenginetorungamein234ndash241gettinginputfromSeeInputgettingfrombrowserhowitaccessesinformation225ndash226

Bytesbreakingfiles85conventionsforencoding80ndash81defined78dissectingcode82ndash84dissectingoutput82

CC3algorithmsuper()function183Cardinalnumberslists120ndash121137caret(^)characterviewoutput11catcommandprintwholefile57252278ndash279cdcommandchangedirectorymacOSLinux251overviewof258ndash260Windows252

cd~command255CharactersencodingSeeStringsbytesandcharacterencodingsimportanceoflearningnamesof76fortruthterms96ndash97

Checklistcreatingfunction62ChildclassesSeeInheritancevscompositionClassesaddsconsistencytoprogram146asblueprintsfornewmini-modules149codeandtestinOOP167ndash169

designhierarchyinOOP166ndash167inheritancevscompositionSeeInheritancevscompositionobject-orientedphrasedrill152ndash153object-orientedreadingtest154ndash155object-orientedworddrill152researchingPython137similaritytomodules147ndash148styling189astemplatesmintingnewobjects186

CLI(commandlineinterface)usingonGUI261closecommandclosefile52ndash53Codeavoidhardcodingfilenames48blocksof106ndash107classestesting167ndash169createonelineof57findingerrorsin132inheritancevscompositionforreusable185OOPanalysisanddesign170ndash176parser211ndash214practicingEnglishto155reading132readingbackwardSeeReadingcodebackwardreadingphrases156refactoringforgothonwebgame234ndash239researchingpieceof78styling190testingotherprogrammerrsquos94typingintoTerminalPowerShell50

Colon()creatingfunctions61ndash62Colorsintexteditors12Command-linecrashcoursechangedirectory(cd)258ndash261copyfile(cp)272ndash275

exityourterminal(exit)282howtouseappendix248ndash249introduction248listdirectory(ls)261ndash265makedirectory(mkdir)255ndash257makeemptyfiles(touchNew-Item)271ndash272memorizingthings249movearound(pushdpopd)268ndash271movefile(mv)275ndash276pathsfoldersdirectories(pwd)253ndash255PowerShellreferences283removedirectory(rmdir)265ndash268removefile(rm)280ndash281setup249ndash253streamfile(cat)278ndash279UnixBashreferences283viewfile(lessmore)277ndash278

Commandlineinterface(CLI)usingonGUI261Commandsconvertingargumentstostrings44asfunctionsandmethods50learning44

Commentsaddingwhenreadingcode132creatingfunctionswith65ndash66designingdebuggingwith127functionsfileswith69gettinghelpwithdocumentation92is-ahas-arelationshipsusing159ndash160readingwritingfilesusing53usinginPython14ndash15variablenames21writinggood190writingwhenyoudonotunderstandcode29124

Composition

Compositiondefined152overviewof184ndash185whentouseinheritanceor185

Connectionsweb225ndash226Conventionsforencodingtext80ndash81Copyingfileswritingscriptfor56ndash58cpcopyfileordirectorymacOSLinux251overviewof272ndash275Windows252

curlcommandgeneraterequesttypes232

DDatastructuresdictionariesas140ndash144listsascommon136ndash137

Datatypeslistof129DBES(DecodeBytesEncodeStrings)dissectingcode83ndash84Debuggingdesigningand126ndash127fixingerrorsinfirstwebsite219refactoredcode241

Decisionsmaking108ndash110dedent()function-stylestrings170ndash175def(createfunction)branchesandfunctions122ndash124creategameengine239ndash241defined152filesworkingwithfunctions68ndash70functionscanreturnsomething72ndash74functionsworkingwithvariables90ndash93is-ahas-arelationships159ndash160overviewof60ndash62inreadingtest154ndash155

delkeyworddeletefromdictionary141Designinganddebugging126ndash127dict

howformswork227understandingdictionaries140ndash144

Dictionariesexampleof141ndash143functionsof143ndash144listsvs140ndash141modulessimilarto146ndash147storescenesbynamein175

diefunctionif-statementrules126dir-rfindfilesinWindows253DirectoriescausesofImportErrors209ldquoHelloWorldrdquowebapplication217LinuxmacOScommand-linefor251skeletonprojectSeeSkeletonprojectdirectoryWindowscommand-linefor252

DjangoTutorial244Documentationcheckoutprojectsbuildsomethingusing244gettinghelpwithcomments92writinggoodcomments190

Dot()operator146ndash148193Doublebacklash()36Double-quotesSee(double-quotes)

Eechoprintsomearguments252253Elementsaccessinglist120ndash121elif

branchesandfunctions122ndash124andelse107makingdecisions108ndash110

else

branchesandfunctions122ndash124andif-statement106ndash107makingdecisions108ndash110rulesforif-statements126

Encodingsbytescharacter80ndash85envcommandlookatyourenvironment252EqualoperatorSee==(equal)operatorErrormessagesbuildingfirstwebsite218ndash219EOFError155ImportErrorSeeImportErrorsNameError47ParserError211ndash214printing29forspacesbetweentriple-quotes33forspellingmistakes33ValueErrorSeeValueErrorsvariablenames21viewingoutputinfirstprogram11whenmakingscriptshorter58

Escapesequencesfordifferentcharactersinstrings34ndash35practicing87readingandwritingfiles54reviewing130supportedbyPython35

exceptkeywordexceptions206Exceptionshowtoraise211ndash214andnumbers206

existscommandcopyingfiles56ndash58exitcommandexitshell124252282exportcommandexportnewenvironmentvariable252

F

Ffcharacterembeddingvariablesinsidestrings24ndash25promptingandpassing46ndash47inreadline()70usingwithfunctions69

Falsekeywordavoidquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98

Featuresaddingtoscript42alsocalledmodules42ndash43

FileTransferProtocol(FTP)andURLs225Filenames48ndash50Filescopying56ndash58creating50andfunctions68ndash70LinuxmacOScommand-linefor251ndash252reading48ndash50readingandwriting52ndash54Windowscommand-linefor252ndash253

findcommandfiles252Firstprogramcreate8ndash12flaskframeworkcreatebasictemplatesforwebsite219ndash221creategameengine239ndash241fixerrors218ndash219ImportErrorafterinstalling222installingforfirstwebsite216makeldquoHelloWorldrdquowebapplication216ndash217testingtricksforcreatingfakesessions242webpyvs221

whatisgoingon218FLASK_DEBUGnotsafetoactivateonInternet219Flowcharts132FoldersSeeDirectoriesfooOOP152for-loops

buildinglistswith112ndash114rulesfor126whentouselists137while-loopsvs118

forOOP154ndash155forfiles253formatfunction30ndash31Formatstringsformatterformat()30oldstyle130ndash131overviewof24ndash25readingandwritingfiles54

format()syntaxformattingstrings26ndash2730Formsautomatedtestsfor232creatingHTML227ndash229howtheywork226ndash227

FTP(FileTransferProtocol)andURLs225Functionsaccessinginmodulewith(dot)operator146ndash147alsocalledmethodscommands50branchesand122ndash124canreturnsomething72ndash74createchecklistfor62andfiles68ndash70overviewof60ndash62practicing87ndash8890ndash93readingcode132

replicatingimplicitinheritance184ndash185styling189usingprintvsreturnin93andvariables64ndash6687ndash88viewingcalls137

GGamestartofyourwebcreatingengine239ndash241overviewof234refactoring234ndash239yourfinalexam241ndash242

GamesanalysisanddesignSeeObject-orientedanalysisanddesignmakingyour188ndash191

gothonwebprojectanalysisofsimplegameengine165ndash169codefor170ndash176creatinglayouttemplate234ndash239makingintofirstwebapplication217ndash221refactoringcodecreatingwebenginetorun234ndash241

Grammarmakingsentences211215Greater-than-equal(gt=)operator16ndash1797Greaterthan(gt)operator16ndash1791grepcommandfindthingsinsidefiles252GUI(graphicaluserinterface)usingCLIon261

HHardcodedfilenamesavoid48has-arelationships152158ndash162ldquoHelloWorldrdquowebapplicationcreatebasictemplates219ndash221fixingerrors218ndash219

Helpcreatesystemfor242

gettingmodule92helpcommandWindows253helpctrcommandWindows253Hierarchyclass166ndash169hostname

mycomputerrsquosnetworkname251252understandURLs225

HTMLcreatebasictemplatesforwebsite219ndash221createforms227ndash229creategameengine239ndash241improveappearanceof242research232understandresponse226

HTTPrequests218244researchHTTPREC232understandURLs225

IIDLEavoidusing1231if-elsetry-exceptvs209if-statements

branchesandfunctions122ndash124elseand106ndash107loopsandlists112ndash114makedecisions83ndash84108ndash110overviewof104ndash105readcode132rulesfor126

Implicitinheritancecombinewithothertypesofinheritance182compositionvs184ndash185overviewof178ndash179

import

addfeaturestoscript42copyfiles56ndash58filewithmodules146makeagameyourself188objectsassimilarto148ndash149

ImportErrorsafterinstallingflask222causesof209242createskeletonprojectdirectory199

Incrementby(+=)operator69ndash70105Indentation61ndash62106index()

creategameengine239ndash241createHTMLforms229howformswork227

indexGEThandler224Inheritanceavoidmultiple178183185object-orientedphrasedrill152object-orientedreadingtest154ndash155object-orientedworddrill152

Inheritancevscompositionalterbehaviorbeforeorafter180ndash181implicitinheritance179overrideexplicitly180overviewof178reasonforsuper()183threekindsofinheritancecombined182ndash183understandcomposition184ndash185understandinheritance178ndash179usinginheritancevscomposition185usingsuper()with__init__()183

__init__functioninitializingnewlycreatedemptyobject149

inis-ahas-arelationships159ndash162runningreliablyforparentclass162tryingnottodotoomuchin189usingselfwhenmakingfunctionsforclasses151usingsuper()in183

input()

askingquestions38ndash39enteringownvalues74parameterto(gt)124parametersunpackingvariables42ndash44promptingandpassing46ndash47promptingpeople40ndash41readingfiles48ndash50

Inputadvanceduserourgamelexicon204ndash206overviewof204testfirstchallenge206ndash207whatyoushouldtest207ndash209

Inputgettingfrombrowserbreakingit232creatingHTMLforms227ndash229creatinglayouttemplate229ndash230howformswork226ndash227howwebworks224ndash226writingautomatedtestsforforms232

ltinputgttags229ndash230Instance152ndash153Instantiation148ndash149Internetflaskdebuggermodenotsafeon219Internetresearchcheckoutprojectstrytobuildsomething244findthings5ndash6functionsandfiles69importstatement57

object-orientedprogramming137151pydoc40ndash41readingfiles49

int()functionconvertingcommandlineargumentstrings44IPaddressesandURLs225is-arelationships152158ndash162

JJinja2Documentationtemplatelanguage221

KKeywordslistof128ndash129Kivy244

LLayouttemplatecreate232LearnCTheHardWay244LearnRubyTheHardWay244len()function5658lesscommandviewfileinmacOSLinux252277ndash278Less-than-equal(lt=)operator16ndash1797Lessthan(lt)operator16ndash17LexiconcreatinggamemakesentencesSeeSentencesmakingoverviewof204ndash206testfirstchallenge206ndash207whatyoushouldtest207ndash209

Librariesdefined43LinuxmacOSalternativetexteditorsfor7getterminalopenandworking250ndash251projectskeletonsetup192ndash194setupexercise4ndash5

LinuxmacOScommand-linecatstreamfile278ndash279

cdchangedirectory258ndash259261cpcopyfileordirectory272274ndash275exitexitshell282lessviewfile277ndash278listofcommands251ndash252lslistdirectory262265mkdirmakedirectory256ndash257mvmovefileordirectory275277pushdpopd(movedirectory)268ndash271pwdprintworkingdirectory253ndash255rmstreamfile278ndash279rmdirremovedirectory266268

Listsaccesselementsof120ndash121buildusingfor-loops112ndash114doingthingsto134ndash138making2-D114processinglistsofthings78whentouse137

localhost

buildfirstwebsite218221webconnection225

Logicmemorizing96ndash98practicingBoolean100ndash102

Loginresearchingwebapplication242Lookuptablesdictionariesas144Loopsandlists112ndash114for-loopsSeefor-loopsmakinginfinite124rulesfor126ndash127while-loopsSeewhile-loops

lpthwvirtualenvironmentskeletonproject193195

lslistdirectorymacOSLinux251overviewof261ndash265Windows252

MmacOSSeeLinuxmacOSmainfunctiondissectingcode83manreadmanualpageinmacOSLinux252Mapclassgothonwebprojectcode171storingscenesbynameindictionary175

Mapsanalysisofsimplegameengine165completinggame242withdictionaries143ndash144

matchfunctionparsercode212Math16ndash1839Memorizationofcommandsusingindexcards251ndash253learningcommandline249oflogic96ndash98tipsfor96

Methodresolutionorder(MRO)super()183Methodsalsocalledfunctionsandcommands50functionsvs189

Minus(--)operator16ndash17mkdirmakedirectorymacOSLinux251overviewof255ndash257Windows252

Modifiersreadingandwritingfiles54ModulescausesofImportErrors209

gettinghelpfor92overviewof146ndash147replicatingimplicitinheritancein184ndash185usingclassesvs147ndash148

morecommandviewfileinWindows252278MRO(methodresolutionorder)super()183Multipleinheritanceavoid178183185mvcommandmovefileordirectorymacOSLinux251overviewof275ndash277Windows252

NNameErrormessage47Namescreatingfunction62189definemodules42ndash43filenames48ndash50importanceoflearningsymbol76variable20ndash2260ndash62

NaturalLanguageToolKit244Nestedstructureslistsas112rulesforif-statements126

new-itemcommandcreateemptyfilesinWindows271ndash272Noneforsomefunctions93nosetestscommandautomatedtests201ndash203automatedtestsforforms231createskeletonprojectdirectory197ndash199syntaxerror203

not

inBooleanlogic100ndash102intruthtables97ndash98

astruthterm97Notequal(=)operator97ndash98100ndash102Nounsobject-orientedprogramming164ndash167Numbersaccesselementsoflists120ndash121exceptionsand206indexlistsinto140ndash141inputtodomath39andmath16ndash18betweenrangeofnumbers110roundingfloatingpoint25

OObject-orientedanalysisanddesignSeealsoGamestartofyourwebanalysisofsimplegameengine165codeclassesandtesttorunthem167ndash169codeforldquoGothonsfromPlanetPercal25rdquo170ndash176createclasshierarchyobjectmapforconcepts166ndash167extractresearchkeyconcepts166overviewof164ndash165repeatandrefine169topdownvsbottomup169whatyoushouldsee176writeordrawaboutproblem165

Object-orientedprogramming(OOP)inheritancevscompositionSeeInheritancevscompositionPythonas146research137151speak152ndash156

Objectsclassesastemplatesthatmintnew186makesentenceswith210ndash211object-orientedphrasedrill152ndash153object-orientedworddrill152parsercode212ndash215

similartoimport148ndash149Octothorpe()character1214ndash1517opencommandreadingandwritingfiles52ndash54OperatorsfindingmorePythonequality102listof131ndash132math16ndash17variablename20ndash22

or

inBooleanlogic100ndash102intruthtables97ndash98astruthterm96

Ordermaintainwithlists137Ordinalnumberslists120ndash121Outputoffirstprogram10ndash11ldquoHelloWorldrdquowebapplication217

override()functioninheritance189

PPandas244Paragraphsif-statementrules126Parametersreadingandwritingfiles54ParentclassesSeeInheritancevscompositionParsercode211ndash214playingwith214ndash215

ParserErrorexception211ndash214Passingpromptingand46ndash47PEMDASacronymorderofmathoperations18Percent()operator1617ndash18Phrasedrillsobject-oriented152ndash156pip36(orjustpip)createskeletonprojectdirectory192ndash195198ndash199installflasktobuildfirstwebsite216

planispherepyfile234ndash238

planisphere_testspyfile238ndash239Plus(+)operator16ndash1754popdcommandpopdirectorymacOSLinux251overviewof268ndash271Windows252

Portswebconnections225POSTautomatedtestsforforms231creatingHTMLforms227ndash229

Pound()character1214ndash1517PowerShellcreategameengine240infirstprogram11ndash12references283typingcodeinto50Windows10setupfor3ndash4195250ndash251

print

debugwith127readcodeusing132whenfunctionsusereturnvs93

Printstringswithmorecomplicatedformatting30ndash31moreexercisesin28ndash2932ndash33usingescapesequences34ndash36variables24ndash25

print_a_linepassincurrentlinenumber68ndash69print_linefunctiondissectingcode83ndash84print_twofunctioncreatefunctions60ndash61Programminglanguagesadvicefromoldprogrammer246ndash247checkoutprojectstrytobuildsomething244howtolearnnew245learningcommandlineSeeCommand-linecrashcourse

Projectskeleton192ndash194Promptsidentifyinappendixexercises254andpassing46ndash47people40ndash41

Prototypelanguages186Pseudocodetestfirstusing207pushdcommandpushdirectorymacOSLinux251overviewof268ndash271Windows252

pwdcommandprintworkingdirectorymacOSLinux251overviewof253ndash255Windows252

pyfilespassingvariablestoscript42ndash44pydoccommandpromptpeople40ndash41PyGame244PYTHONPATHenvironmentvariable240

Qquit()functionreloadPythonafter92

Rraisekeywordexceptions211213ndash214range()functionloops114Rawbytes7982ndash84readcommandreadcontentsoffile52ndash54Readingcode132codeoutloud190files48ndash50andwritingfiles52ndash54

Readingcodebackwardcommentsandpoundcharacters14

defined88printing29reasonsfor15understandinghowto22

readline()function52ndash53687083Refactoringcode234ndash239render_template()function220ndash221requestargsforms227Requestswebgeneratingtypesofwithcurl232learnclientsideofHTTP244process224ndash225understand225

Responsesweb226return

functions72ndash74object-orientedreadingtest155whenfunctionsuseprintvs93

rmstreamfile280ndash281rmdircommandremovedirectorymacOSLinux251overviewof265ndash268Windows252

Roomclassautomatedtests201ndash203creategameengine239ndash241refactorcodeforgothonwebgame234ndash239

round()functionfloatingpointnumbers25Rulesforif-statements126forloops126ndash127whentouseinheritanceorcomposition185

runascommanddangerinwindows252

S

Scanninginputlexicontuples205209Scenes(rooms)analysisofsimplegameengine165ndash167codeclassesforsimplegame167ndash169gothonwebprojectcode170ndash176makinggameyourself188ndash191whatyoushouldsee176

SciPy244ScraPy244Scriptslinkingfunctionsto61makingdecisions107passingvariablesto42ndash44

SearchenginesfindingthingsonInternet5ndash6howtotype(octothorp)character15

seek()functiondefined52ndash53doesnotsetcurrentlineto070researchforfile69

select-stringcommandfindthingsinsideWindowsfiles253self

__init__function148151is-ahas-arelationshipsand159ndash160object-orientedlanguage152ndash155

Sentencesmakingbreakingup205exceptions211grammar211matchandpeek210ndash211overviewof210parsercode211ndash215whatyoushouldtest215

Servershowbrowsersaccessinformationon226

setcommandexportsetnewenvironmentvariableinWindows253Setupexercisealternativetexteditors6ndash7findingthingsonInternet5ndash6Linux4ndash5macOS2ndash3overviewof2warningsforbeginners6Windows3ndash4

setuppyfileskeletonprojectdirectory196198ndash199Single-equal(=)operator21Single-quotesSee(single-quotes)Skeletonprojectdirectoryautomatedtesting200ndash203creatingdirectorystructure195ndash197macOSLinuxsetup192ndash194overviewof192requiredquiz198testingsetup197ndash198using198Windows10setup194ndash195

skipkeywordparsercode213Slash()character16ndash17257Spaceaddingaroundoperatorsforeasierreading22makecodereadablewithvertical190

Spellingmistakeserrormessagesfor33Stopwordsparsercode213Stringsacrossmultiplelines34ndash36complicatedformattingof30ndash31convertcommandlineargumentsto44decodebytesandencode83ndash84embedvariablesinside24ndash25

exerciseinprinting28ndash29listofescapesequencesfor130listofoldstyleformatsfor130ndash131listsmixedwith135ndash136poundcharactersin15readwritefilesin54startnewlinein33andtext26ndash27understanding26asUTF-8encodedsequenceofcharacters82

Stringsbytesandcharacterencodingsbreakingit85dissectcode82ndash84dissectoutput82encodingsdeepdive84ndash85initialresearch78ndash80overviewof78switchesandconventions80ndash81

Stylingcode190functionsandclasses189

Subjectparsercode212ndash215ofsentences210ndash211

sudocommand252super()functioninheritance180ndash183Switches80ndash81Symbolsdatatypes129escapesequencesforstrings130keywords128ndash129learningnamesof76oldstylestringformats130ndash131operators131ndash132readingcode132

SyntaxErrormessageEOL58invalidsyntax1293promptingandpassing47pydoc41viewingoutputinfirstprogram11

Systemsitepackagessetupforskeletonproject193

TTablesdictionariesaslookup144truth97ndash98

Templatescreatebasic219ndash221creategameengine239ndash241createHTMLforms229createlayout229ndash230

templatesindexhtmlfile219ndash221229ndash230templateslayouthtmlfile230TensorFlow244Terminalgettingopenandworking250ndash251Linuxsetup5macOSsetup2ndash3typingcodeinto50whatyoushouldseeinfirstprogram9ndash11Windowssetup3ndash4

Terminologytruth96ndash97webapplication225ndash226

Testcasewriting200ndash201Testfirstprogrammingtactic206ndash207Test_directionstestcase207ndash209TestsSeealsoAutomatedtestsBooleanlogic100ndash102

codeforclassesinOOP168ndash169object-orientedreading153ndash155otherprogrammerrsquoscode94session-basedgameengine241skeletonprojectdirectorysetup197ndash198tricksforcreatingfakesessionsinside242

testsapp_testspy231Testtxtfilecopyingfiles56ndash58Textreadingfiles48ndash50andstrings26ndash27

Texteditorsalternative6ndash7gettingcolorsin12Linuxsetup4ndash5macOSsetup2

Thingsgettingthingsfrom149ndash150TopdownprocessOOPdesign164vsbottomup169

touchcommandmakeemptyfilesinmacOSLinux271ndash272Tracingvariablesreadingcode132Triple-quotes()See(triple-quotes)Triple-single-quotes()36Truekeywordavoidputtingquotesaround31object-orientedreadingtest154ndash155intruthtables97ndash98astruthterm97

truncatecommand52ndash54Truthtables97ndash98terms96ndash97

try-exceptif-elsevs209

trykeywordexceptions206Tupleslexicon205typecommandprintwholefileinWindows252

UUnderscore(_)character20ndash2162189Unicode81URLs(UniformResourceLocators)buildfirstwebsite218createHTMLforms228howformswork227overviewof225

UserinputSeeInputadvanceduserUserWarningwhenrunningnosetests203UTF-16standard84ndash85UTF-8standardcomparingUTF-16UTF-32to84ndash85dissectingoutput82encodingtextinPython81fixingterminalunabletodisplay79stringsinPython82ndash84

VValueErrorsandnumbers206parametersunpackingvariables44promptingpassing47

Variablesaccessinmodule146ndash147avoidmoduleorglobal189andfunctions64ndash66for-loopusingundefined114andnames20ndash22andnamescodefunctions60ndash62passingtoscript42ndash44

practicing90ndash93printing24ndash25promptingandpassing46ndash47readingcode132temporarilyinsidefunctions87ndash88writingstringswithtext26ndash27

venvsdirectoryskeletonprojectsetup193ndash195VerbsanalyzeclasshierarchyinOOP165extractkeyconceptsinOOP164makesentenceswith210ndash211parsercode212ndash215

virtualenv192ndash193194

WWarningsforbeginners5ndash6setup2

Webbreakingapplications232howitworks224ndash226learnclientsideof244startofyourgameSeeGamestartofyourweb

Websiteyourfirstcreatebasictemplates219ndash221fixingerrors218ndash219installflaskframework216makeldquoHelloWorldrdquowebapplication216ndash217whatisgoingon218

while-loops

overviewof116ndash118readingcode132rules126whentobreakruleaboutnotusing138

whileTruemakeinfiniteloop124Windows

Windowsalternativetexteditorsfor7setupexercise3ndash4skeletonprojectdirectorysetup194ndash195

Windowscommand-linecatstreamfile259ndash261278ndash279cpcopyfileordirectory272ndash275exitexitshell282gettingPowerShellopenandworkingfor250ndash251listofcommands252ndash253lslistdirectory262ndash265macOSsetup2moreviewfile278mvmovefileordirectory275ndash277pushdpopd(movedirectory)269ndash271pwdprintworkingdirectory254ndash255rmstreamfile278ndash279rmdirremovedirectory266ndash268

Worddrillsobject-oriented152ndash155wordspopfunction93Writeformulasusingfunctions74andreadfiles52ndash54

Xxargscommandexecutearguments252

CodeSnippets

ManytitlesincludeprogrammingcodeorconfigurationexamplesTooptimizethepresentationoftheseelementsviewtheeBookinsingle-columnlandscapemodeandadjustthefontsizetothesmallestsettingInadditiontopresentingcodeandconfigurationsinthereflowabletextformatwehaveincludedimagesofthecodethatmimicthepresentationfoundintheprintbookthereforewherethereflowableformatmaycompromisethepresentationofthecodelistingyouwillseealdquoClickheretoviewcodeimagerdquolinkClickthelinktoviewtheprint-fidelitycodeimageToreturntothepreviouspageviewedclicktheBackbuttononyourdeviceorapp

  • About This eBook
  • Title Page
  • Copyright Page
  • Contents
  • Preface
    • Improvements in the Python 3 Edition
    • The Hard Way Is Easier
      • Reading and Writing
      • Attention to Detail
      • Spotting Differences
      • Ask Donrsquot Stare
      • Do Not Copy-Paste
      • Using the Included Videos
      • A Note on Practice and Persistence
        • Acknowledgments
          • Exercise 0 The Setup
            • macOS
              • macOS What You Should See
                • Windows
                  • Windows What You Should See
                    • Linux
                      • Linux What You Should See
                        • Finding Things on the Internet
                        • Warnings for Beginners
                        • Alternative Text Editors
                          • Exercise 1 A Good First Program
                            • What You Should See
                            • Study Drills
                            • Common Student Questions
                              • Exercise 2 Comments and Pound Characters
                                • What You Should See
                                • Study Drills
                                • Common Student Questions
                                  • Exercise 3 Numbers and Math
                                    • What You Should See
                                    • Study Drills
                                    • Common Student Questions
                                      • Exercise 4 Variables and Names
                                        • What You Should See
                                        • Study Drills
                                        • Common Student Questions
                                          • Exercise 5 More Variables and Printing
                                            • What You Should See
                                            • Study Drills
                                            • Common Student Questions
                                              • Exercise 6 Strings and Text
                                                • What You Should See
                                                • Study Drills
                                                • Break It
                                                • Common Student Questions
                                                  • Exercise 7 More Printing
                                                    • What You Should See
                                                    • Study Drills
                                                    • Break It
                                                    • Common Student Questions
                                                      • Exercise 8 Printing Printing
                                                        • What You Should See
                                                        • Study Drills
                                                        • Common Student Questions
                                                          • Exercise 9 Printing Printing Printing
                                                            • What You Should See
                                                            • Study Drills
                                                            • Common Student Questions
                                                              • Exercise 10 What Was That
                                                                • What You Should See
                                                                • Escape Sequences
                                                                • Study Drills
                                                                • Common Student Questions
                                                                  • Exercise 11 Asking Questions
                                                                    • What You Should See
                                                                    • Study Drills
                                                                    • Common Student Questions
                                                                      • Exercise 12 Prompting People
                                                                        • What You Should See
                                                                        • Study Drills
                                                                        • Common Student Questions
                                                                          • Exercise 13 Parameters Unpacking Variables
                                                                            • Hold Up Features Have Another Name
                                                                            • What You Should See
                                                                            • Study Drills
                                                                            • Common Student Questions
                                                                              • Exercise 14 Prompting and Passing
                                                                                • What You Should See
                                                                                • Study Drills
                                                                                • Common Student Questions
                                                                                  • Exercise 15 Reading Files
                                                                                    • What You Should See
                                                                                    • Study Drills
                                                                                    • Common Student Questions
                                                                                      • Exercise 16 Reading and Writing Files
                                                                                        • What You Should See
                                                                                        • Study Drills
                                                                                        • Common Student Questions
                                                                                          • Exercise 17 More Files
                                                                                            • What You Should See
                                                                                            • Study Drills
                                                                                            • Common Student Questions
                                                                                              • Exercise 18 Names Variables Code Functions
                                                                                                • What You Should See
                                                                                                • Study Drills
                                                                                                • Common Student Questions
                                                                                                  • Exercise 19 Functions and Variables
                                                                                                    • What You Should See
                                                                                                    • Study Drills
                                                                                                    • Common Student Questions
                                                                                                      • Exercise 20 Functions and Files
                                                                                                        • What You Should See
                                                                                                        • Study Drills
                                                                                                        • Common Student Questions
                                                                                                          • Exercise 21 Functions Can Return Something
                                                                                                            • What You Should See
                                                                                                            • Study Drills
                                                                                                            • Common Student Questions
                                                                                                              • Exercise 22 What Do You Know So Far
                                                                                                                • What You Are Learning
                                                                                                                  • Exercise 23 Strings Bytes and Character Encodings
                                                                                                                    • Initial Research
                                                                                                                    • Switches Conventions and Encodings
                                                                                                                    • Disecting the Output
                                                                                                                    • Disecting the Code
                                                                                                                    • Encodings Deep Dive
                                                                                                                    • Breaking It
                                                                                                                      • Exercise 24 More Practice
                                                                                                                        • What You Should See
                                                                                                                        • Study Drills
                                                                                                                        • Common Student Questions
                                                                                                                          • Exercise 25 Even More Practice
                                                                                                                            • What You Should See
                                                                                                                            • Study Drills
                                                                                                                            • Common Student Questions
                                                                                                                              • Exercise 26 Congratulations Take a Test
                                                                                                                                • Common Student Questions
                                                                                                                                  • Exercise 27 Memorizing Logic
                                                                                                                                    • The Truth Terms
                                                                                                                                    • The Truth Tables
                                                                                                                                    • Common Student Questions
                                                                                                                                      • Exercise 28 Boolean Practice
                                                                                                                                        • What You Should See
                                                                                                                                        • Study Drills
                                                                                                                                        • Common Student Questions
                                                                                                                                          • Exercise 29 What If
                                                                                                                                            • What You Should See
                                                                                                                                            • Study Drills
                                                                                                                                            • Common Student Questions
                                                                                                                                              • Exercise 30 Else and If
                                                                                                                                                • What You Should See
                                                                                                                                                • Study Drills
                                                                                                                                                • Common Student Questions
                                                                                                                                                  • Exercise 31 Making Decisions
                                                                                                                                                    • What You Should See
                                                                                                                                                    • Study Drills
                                                                                                                                                    • Common Student Questions
                                                                                                                                                      • Exercise 32 Loops and Lists
                                                                                                                                                        • What You Should See
                                                                                                                                                        • Study Drills
                                                                                                                                                        • Common Student Questions
                                                                                                                                                          • Exercise 33 While Loops
                                                                                                                                                            • What You Should See
                                                                                                                                                            • Study Drills
                                                                                                                                                            • Common Student Questions
                                                                                                                                                              • Exercise 34 Accessing Elements of Lists
                                                                                                                                                                • Study Drills
                                                                                                                                                                  • Exercise 35 Branches and Functions
                                                                                                                                                                    • What You Should See
                                                                                                                                                                    • Study Drills
                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                      • Exercise 36 Designing and Debugging
                                                                                                                                                                        • Rules for if-statements
                                                                                                                                                                        • Rules for Loops
                                                                                                                                                                        • Tips for Debugging
                                                                                                                                                                        • Homework
                                                                                                                                                                          • Exercise 37 Symbol Review
                                                                                                                                                                            • Keywords
                                                                                                                                                                            • Data Types
                                                                                                                                                                            • String Escape Sequences
                                                                                                                                                                            • Old Style String Formats
                                                                                                                                                                            • Operators
                                                                                                                                                                            • Reading Code
                                                                                                                                                                            • Study Drills
                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                              • Exercise 38 Doing Things to Lists
                                                                                                                                                                                • What You Should See
                                                                                                                                                                                • What Lists Can Do
                                                                                                                                                                                • When to Use Lists
                                                                                                                                                                                • Study Drills
                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                  • Exercise 39 Dictionaries Oh Lovely Dictionaries
                                                                                                                                                                                    • A Dictionary Example
                                                                                                                                                                                    • What You Should See
                                                                                                                                                                                    • What Dictionaries Can Do
                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                      • Exercise 40 Modules Classes and Objects
                                                                                                                                                                                        • Modules Are Like Dictionaries
                                                                                                                                                                                          • Classes Are Like Modules
                                                                                                                                                                                          • Objects Are Like Import
                                                                                                                                                                                          • Getting Things from Things
                                                                                                                                                                                          • A First Class Example
                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                              • Exercise 41 Learning to Speak Object-Oriented
                                                                                                                                                                                                • Word Drills
                                                                                                                                                                                                • Phrase Drills
                                                                                                                                                                                                • Combined Drills
                                                                                                                                                                                                • A Reading Test
                                                                                                                                                                                                • Practice English to Code
                                                                                                                                                                                                • Reading More Code
                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                  • Exercise 42 Is-A Has-A Objects and Classes
                                                                                                                                                                                                    • How This Looks in Code
                                                                                                                                                                                                    • About class Name(object)
                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                      • Exercise 43 Basic Object-Oriented Analysis and Design
                                                                                                                                                                                                        • The Analysis of a Simple Game Engine
                                                                                                                                                                                                          • Write or Draw About the Problem
                                                                                                                                                                                                          • Extract Key Concepts and Research Them
                                                                                                                                                                                                          • Create a Class Hierarchy and Object Map for the Concepts
                                                                                                                                                                                                          • Code the Classes and a Test to Run Them
                                                                                                                                                                                                          • Repeat and Refine
                                                                                                                                                                                                            • Top Down versus Bottom Up
                                                                                                                                                                                                            • The Code for ldquoGothons from Planet Percal 25rdquo
                                                                                                                                                                                                            • What You Should See
                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                            • Common Student Questions
                                                                                                                                                                                                              • Exercise 44 Inheritance versus Composition
                                                                                                                                                                                                                • What Is Inheritance
                                                                                                                                                                                                                  • Implicit Inheritance
                                                                                                                                                                                                                  • Override Explicitly
                                                                                                                                                                                                                  • Alter Before or After
                                                                                                                                                                                                                  • All Three Combined
                                                                                                                                                                                                                    • The Reason for super()
                                                                                                                                                                                                                      • Using super() with __init__
                                                                                                                                                                                                                        • Composition
                                                                                                                                                                                                                        • When to Use Inheritance or Composition
                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                          • Exercise 45 You Make a Game
                                                                                                                                                                                                                            • Evaluating Your Game
                                                                                                                                                                                                                            • Function Style
                                                                                                                                                                                                                            • Class Style
                                                                                                                                                                                                                            • Code Style
                                                                                                                                                                                                                            • Good Comments
                                                                                                                                                                                                                            • Evaluate Your Game
                                                                                                                                                                                                                              • Exercise 46 A Project Skeleton
                                                                                                                                                                                                                                • macOSLinux Setup
                                                                                                                                                                                                                                • Windows 10 Setup
                                                                                                                                                                                                                                • Creating the Skeleton Project Directory
                                                                                                                                                                                                                                  • Final Directory Structure
                                                                                                                                                                                                                                    • Testing Your Setup
                                                                                                                                                                                                                                    • Using the Skeleton
                                                                                                                                                                                                                                    • Required Quiz
                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                      • Exercise 47 Automated Testing
                                                                                                                                                                                                                                        • Writing a Test Case
                                                                                                                                                                                                                                        • Testing Guidelines
                                                                                                                                                                                                                                        • What You Should See
                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                          • Exercise 48 Advanced User Input
                                                                                                                                                                                                                                            • Our Game Lexicon
                                                                                                                                                                                                                                              • Breaking Up a Sentence
                                                                                                                                                                                                                                              • Lexicon Tuples
                                                                                                                                                                                                                                              • Scanning Input
                                                                                                                                                                                                                                              • Exceptions and Numbers
                                                                                                                                                                                                                                                • A Test First Challenge
                                                                                                                                                                                                                                                • What You Should Test
                                                                                                                                                                                                                                                • Study Drills
                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                  • Exercise 49 Making Sentences
                                                                                                                                                                                                                                                    • Match and Peek
                                                                                                                                                                                                                                                    • The Sentence Grammar
                                                                                                                                                                                                                                                    • A Word on Exceptions
                                                                                                                                                                                                                                                    • The Parser Code
                                                                                                                                                                                                                                                    • Playing with the Parser
                                                                                                                                                                                                                                                    • What You Should Test
                                                                                                                                                                                                                                                    • Study Drills
                                                                                                                                                                                                                                                    • Common Student Questions
                                                                                                                                                                                                                                                      • Exercise 50 Your First Website
                                                                                                                                                                                                                                                        • Installing flask
                                                                                                                                                                                                                                                        • Make a Simple ldquoHello Worldrdquo Project
                                                                                                                                                                                                                                                        • Whatrsquos Going On
                                                                                                                                                                                                                                                        • Fixing Errors
                                                                                                                                                                                                                                                        • Create Basic Templates
                                                                                                                                                                                                                                                        • Study Drills
                                                                                                                                                                                                                                                        • Common Student Questions
                                                                                                                                                                                                                                                          • Exercise 51 Getting Input from a Browser
                                                                                                                                                                                                                                                            • How the Web Works
                                                                                                                                                                                                                                                            • How Forms Work
                                                                                                                                                                                                                                                            • Creating HTML Forms
                                                                                                                                                                                                                                                            • Creating a Layout Template
                                                                                                                                                                                                                                                            • Writing Automated Tests for Forms
                                                                                                                                                                                                                                                            • Study Drills
                                                                                                                                                                                                                                                            • Breaking It
                                                                                                                                                                                                                                                              • Exercise 52 The Start of Your Web Game
                                                                                                                                                                                                                                                                • Refactoring the Exercise 43 Game
                                                                                                                                                                                                                                                                • Creating an Engine
                                                                                                                                                                                                                                                                • Your Final Exam
                                                                                                                                                                                                                                                                • Common Student Questions
                                                                                                                                                                                                                                                                  • Next Steps
                                                                                                                                                                                                                                                                    • How to Learn Any Programming Language
                                                                                                                                                                                                                                                                      • Advice from an Old Programmer
                                                                                                                                                                                                                                                                      • Appendix Command Line Crash Course
                                                                                                                                                                                                                                                                        • Introduction Shut Up and Shell
                                                                                                                                                                                                                                                                          • How to Use This Appendix
                                                                                                                                                                                                                                                                          • You Will Be Memorizing Things
                                                                                                                                                                                                                                                                            • The Setup
                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                • Paths Folders Directories (pwd)
                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                    • If You Get Lost
                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                        • Make a Directory (mkdir)
                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                            • Change Directory (cd)
                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                • List Directory (ls)
                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                    • Remove Directory (rmdir)
                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                        • Moving Around (pushd popd)
                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                            • Making Empty Files (touchNew-Item)
                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                • Copy a File (cp)
                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                    • Moving a File (mv)
                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                        • View a File (lessmore)
                                                                                                                                                                                                                                                                                                                          • Do This
                                                                                                                                                                                                                                                                                                                          • You Learned This
                                                                                                                                                                                                                                                                                                                          • Do More
                                                                                                                                                                                                                                                                                                                            • Stream a File (cat)
                                                                                                                                                                                                                                                                                                                              • Do This
                                                                                                                                                                                                                                                                                                                              • You Learned This
                                                                                                                                                                                                                                                                                                                              • Do More
                                                                                                                                                                                                                                                                                                                                • Removing a File (rm)
                                                                                                                                                                                                                                                                                                                                  • Do This
                                                                                                                                                                                                                                                                                                                                  • You Learned This
                                                                                                                                                                                                                                                                                                                                  • Do More
                                                                                                                                                                                                                                                                                                                                    • Exiting Your Terminal (exit)
                                                                                                                                                                                                                                                                                                                                      • Do This
                                                                                                                                                                                                                                                                                                                                      • You Learned This
                                                                                                                                                                                                                                                                                                                                      • Do More
                                                                                                                                                                                                                                                                                                                                        • Command Line Next Steps
                                                                                                                                                                                                                                                                                                                                          • Unix Bash References
                                                                                                                                                                                                                                                                                                                                          • PowerShell References
                                                                                                                                                                                                                                                                                                                                              • Index
                                                                                                                                                                                                                                                                                                                                              • Code Snippets
Page 6: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 7: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 8: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 9: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 10: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 11: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 12: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 13: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 14: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 15: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 16: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 17: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 18: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 19: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 20: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 21: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 22: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 23: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 24: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 25: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 26: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 27: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 28: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 29: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 30: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 31: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 32: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 33: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 34: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 35: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 36: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 37: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 38: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 39: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 40: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 41: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 42: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 43: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 44: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 45: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 46: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 47: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 48: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 49: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 50: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 51: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 52: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 53: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 54: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 55: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 56: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 57: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 58: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 59: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 60: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 61: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 62: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 63: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 64: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 65: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 66: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 67: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 68: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 69: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 70: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 71: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 72: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 73: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 74: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 75: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 76: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 77: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 78: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 79: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 80: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 81: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 82: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 83: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 84: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 85: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 86: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 87: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 88: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 89: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 90: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 91: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 92: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 93: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 94: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 95: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 96: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 97: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 98: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 99: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 100: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 101: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 102: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 103: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 104: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 105: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 106: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 107: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 108: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 109: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 110: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 111: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 112: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 113: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 114: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 115: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 116: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 117: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 118: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 119: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 120: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 121: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 122: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 123: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 124: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 125: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 126: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 127: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 128: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 129: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 130: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 131: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 132: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 133: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 134: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 135: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 136: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 137: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 138: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 139: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 140: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 141: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 142: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 143: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 144: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 145: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 146: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 147: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 148: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 149: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 150: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 151: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 152: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 153: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 154: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 155: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 156: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 157: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 158: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 159: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 160: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 161: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 162: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 163: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 164: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 165: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 166: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 167: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 168: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 169: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 170: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 171: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 172: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 173: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 174: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 175: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 176: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 177: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 178: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 179: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 180: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 181: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 182: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 183: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 184: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 185: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 186: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 187: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 188: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 189: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 190: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 191: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 192: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 193: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 194: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 195: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 196: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 197: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 198: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 199: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 200: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 201: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 202: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 203: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 204: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 205: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 206: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 207: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 208: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 209: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 210: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 211: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 212: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 213: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 214: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 215: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 216: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 217: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 218: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 219: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 220: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 221: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 222: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 223: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 224: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 225: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 226: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 227: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 228: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 229: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 230: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 231: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 232: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 233: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 234: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 235: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 236: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 237: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 238: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 239: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 240: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 241: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 242: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 243: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 244: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 245: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 246: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 247: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 248: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 249: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 250: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 251: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 252: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 253: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 254: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 255: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 256: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 257: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 258: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 259: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 260: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 261: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 262: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 263: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 264: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 265: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 266: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 267: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 268: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 269: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 270: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 271: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 272: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 273: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 274: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 275: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 276: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 277: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 278: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 279: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 280: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 281: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 282: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 283: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 284: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 285: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 286: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 287: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 288: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 289: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 290: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 291: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 292: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 293: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 294: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 295: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 296: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 297: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 298: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 299: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 300: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 301: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 302: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 303: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 304: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 305: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 306: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 307: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 308: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 309: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 310: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 311: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 312: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 313: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 314: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 315: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 316: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 317: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 318: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 319: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 320: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 321: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 322: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 323: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 324: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 325: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 326: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 327: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 328: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 329: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 330: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 331: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 332: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 333: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 334: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 335: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 336: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 337: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 338: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 339: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code
Page 340: Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code