Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
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