Programming a Primer Coding Fo

135

description

start programming now!

Transcript of Programming a Primer Coding Fo

Page 1: Programming a Primer Coding Fo
Page 2: Programming a Primer Coding Fo

Programming:APrimerCodingforBeginners

Page 3: Programming a Primer Coding Fo

ICPPrimersinElectronicsandComputerScience(ICPPECS)ISSN:2054-4537

SeriesEditor:MarkS.Nixon(UniversityofSouthampton,UK)

Published

Vol.1 DigitalElectronics:APrimerIntroductoryLogicCircuitDesignbyMarkS.Nixon

Vol.2 Programming:APrimer

CodingforBeginnersbyTomBell

Page 4: Programming a Primer Coding Fo
Page 5: Programming a Primer Coding Fo

Programming:APrimerCodingforBeginners

TomBellUniversityofSouthampton,UK

Page 6: Programming a Primer Coding Fo

Publishedby

ImperialCollegePress

57SheltonStreet

CoventGarden

LondonWC2H9HE

Distributedby

WorldScientificPublishingCo.Pte.Ltd.

5TohTuckLink,Singapore596224

USAoffice:27WarrenStreet,Suite401-402,Hackensack,NJ07601

UKoffice:57SheltonStreet,CoventGarden,LondonWC2H9HE

LibraryofCongressCataloging-in-PublicationData

Bell,Tom(Electronicengineer)

Programming:aprimercodingforbeginners/byTomBell(UniversityofSouthampton,UK).

pagescm—(ICPprimersinelectronicsandcomputerscience)

Includesbibliographicalreferencesandindex.

ISBN978-1-78326-706-4(alk.paper)–ISBN978-1-78326-707-1(alk.paper)

1.Computerprogramming.2.Microcomputers—Programming.I.Title.

QA76.6.B43672015

005.1–dc23

2015011283

BritishLibraryCataloguing-in-PublicationData

AcataloguerecordforthisbookisavailablefromtheBritishLibrary.

Copyright©2016byImperialCollegePress

Allrightsreserved.Thisbook,orpartsthereof,maynotbereproducedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recordingoranyinformationstorageandretrievalsystemnowknownortobeinvented,withoutwrittenpermissionfromthePublisher.

Forphotocopyingofmaterialinthisvolume,pleasepayacopyingfeethroughtheCopyrightClearanceCenter,Inc.,222RosewoodDrive,Danvers,MA01923,USA.Inthiscasepermissiontophotocopyisnotrequiredfromthepublisher.

In-houseEditors:ThomasStottor/DipasriSardar

TypesetbyStallionPress

Email:[email protected]

Page 7: Programming a Primer Coding Fo

PrintedinSingapore

Page 8: Programming a Primer Coding Fo

“Anyone who stops learning is old, whether at twenty or eighty. Anyone who keepslearningstaysyoung.”

HenryFord

FounderofFordMotoringCompany

Tomyfriendsandfamily

Page 9: Programming a Primer Coding Fo

Acknowledgements

Many thanks to all the people who have helped me write this book. First, to JasmineBrown and James Sharkey who have spent countless hours before publication readingdraftsandrefiningthem.Theyhavegiventheirtimeandefforttoproofreadingthisbook,andtheirkindnessishugelyappreciated.

Secondly,toJennaWatt,HollieJames,JamesPatterson,GarethClarridge—andmyfather Steve Bell — who have supported me in filtering the content for clarity andhelpfulness,andtheircontributionsaremuchappreciated.

Thirdly,tomyparents,whohavetaughtmetovalueworkhighlyandtohelpothersinwhatIdo.Myfamilyhavebeenincredibleexamplestomeofpeoplewhoserveeachotherandthelocalcommunitythroughpracticalloveandhospitality.

Finally,tomyfriendsatChristChurchSouthamptonwhosupportedmethroughoutthemanymonthsIspentwriting.Theyencouragedmetoworkdiligentlyandhavebeenajoytoknow,loveandgrowwithoverthepastfewyears.

Page 10: Programming a Primer Coding Fo

ContentsAcknowledgements

ReadMeFirst

StartingPoint

Chapter 1 Introduction

WhatisProgramming?

WhyLearntoProgram?

HowdoesaProgramWork?

ProgrammingLanguages

WhatDoINeed?

HowtoWriteaProgram

Questions

BuildingBlocks

Chapter 2 VariablesandBasicOperations

A“HelloWorld”fromPython

Variables

BasicOperations

InputandOutput

Questions

Chapter 3 DecisionsandLoops

Conditions

The‘if’Statement

The‘for’Loop

The‘while’Loop

TheKeywords‘break’and‘continue’

Questions

Chapter 4 Functions

ABiggerandBetterExample

Questions

TakingitFurther

Chapter 5 ClassesandObjects

Page 11: Programming a Primer Coding Fo

Object-OrientedProgramming

DefiningObjectsusingClasses

Inheritance

Questions

Chapter 6 TheGraphicalUserInterface

wxPython

TheMenuBarandButtons

Questions

WebDevelopment

Chapter 7 Sockets,NetworksandtheWorldWideWeb

Networks

NetworkinginPython

SimpleClient/ServerExample

Questions

Chapter 8 HTML,CSSandJavaScript

HTML

CSS

JavaScript

Questions

Chapter 9 PHPandSQL

PHP

SQL

Questions

What’sOutThere?

Chapter 10 AmazingAlgorithms

PageRank

Sorting

ShortestPath

ArtificialIntelligence

Questions

Chapter 11 ProgrammingLanguages,LibrariesandFrameworks

WebIdeas

Page 12: Programming a Primer Coding Fo

MobileIdeas

DesktopIdeas

Questions

Chapter 12 BigIdeas

CloudComputing

BigData

TheInternetofThings

SecurityandDataPrivacy

NewLearningStyles

3DPrinting

WearableTechnologyandNo-TouchInterfaces

Questions

Chapter 13 WheretoGofromHere

Learn

Do

Afterword

AppendixA

CommonProgrammingTerms

Index

Page 13: Programming a Primer Coding Fo

ReadMeFirst

Over thepast fewdecades,computershaveradicallychangedthewaywerunour lives.Theyhave affected the availabilityof information, ourmethodsof communicationwithfriendsandfamily,education,business,healthcareandourstudyoftheuniverse.Withtheavailabilityoftechnologyandtheimmensepoweratthefingertipsofanyonewhocanuseit,programmingliteracyhasbecomeoneofthemostsought-afterskillsontheplanet.

Only recently has computer sciencebecomea core aspect of the school curriculum.This isgreatnews forchildrenandyoungpeople,butwhatabout thosewho’vealreadyfinished those stages in life? What about those who’ve missed the boat? To the vastmajorityofuswhofall into thiscategory, it’sour task tobegin the journeyofgainingafunctional understanding of programming, while acquiring the confidence andcommitmenttoputourideasintocode.

IstillrememberhowIbeganmyjourney.AfewsimplesearchesonGoogleduringmytimeathighschool,suchas“Howtoprogram”,“HowdoIbecomeaniOSdeveloper?”or“HowtobeMarkZuckerberg”.Itwasthesameplacethatitstartsformanyprogrammers,andit’salegitimateplacetostart.Searchfor“LearningtocodeinC”andyou’llfindsomewell-writtenonlinetutorials,orfor“WhichprogramminglanguageshouldI learnfirst?”andyou’llfindsomecriticalandinterestingarticlescomparingJavaScriptwithPythonasastartingpoint.Thisformoflearningisgreatforansweringthosespecificquestionsyouhave as a beginner, but it lacks something essential— it won’t teach you the broadercontextorthetechnicalframeworkintowhichfindingsfromyourownlearningwillfit.Ifyoupickupahefty500-pagetextbookonPythonforbeginners,itwillteachyouPython,butitwon’tmakeyouanagileprogrammer,abletoadaptquicklytosolvenewproblems.

An alternative to this self-study approach is to undertake some kind of formaleducation inprogramming.StudyComputerScienceatdegree level,orgo tocollege tostudySoftwareDevelopment.Thesecanbefantasticcourses,andIgreatlyvaluedmytimeat university, but this option is not available tomany of us.With jobs, families, and/orfinancialconstraintsitcanbeimpossibletospendthreeyearslearningtocode.Ormaybeyou’re at university already, but you chose a different degree and are already halfwaythrough a course in Geography or Fine Arts. Besides, a degree isn’t by any meansnecessary for equipping you to solve the vastmajority of programming challenges outthere—infact,you’refreeandabletodoityourself,justasyouare.

Programming:APrimer addresses this situation. Inwriting thisbook,mygoal is toinspireyou,andtohelpyouharnessyoururgetoinvent,tobuildandtocirculateyourownideas, through teaching you the fundamental concepts behind modern programming. Iwant to help you understand the powerful tools at your disposal, and to offer you aglimpse at the vast ocean of possibilities for changing the world for the better thoughprogramming.Myassumption,therefore,isthatyourapproachispractical,notacademicandthatyouactuallywantyourselforotherstobenefitinsomewayfromwhatyou’llabletodo.Soifyou’reapproachingcodingwitha“cutoutthenonsenseandtellmeonlywhatIneedtoknow”outlook,you’vegottherightbook.

Page 14: Programming a Primer Coding Fo

This is primarily an introduction to the fundamental concepts in computerprogrammingandnotastep-by-steptutorialforsimplylearningaparticularprogramminglanguage.Assuchtherewon’tbedetailedinstructionsonwhattodoinordertogetyourdevelopment environment set up on a range of platforms, nor will there be acomprehensivecoverageofallthefeaturesoftherelevantprogramminglanguages.Onthecontrary, this book is a journey from alienation to familiarity with the ideas behindprogramming. You’ll be introduced to the basic concepts of various programminglanguages,sothatyoucangoawayandlearnafewforyourselfwithease.You’llfindoutabout what the different languages are used for, and how to write powerful programsquickly. Languages for designing powerful websites will be introduced. Databaselanguages,andaselectionofpopularalgorithmswillbeexplained.Inlaterchapters,we’lltakealookatwheretechnologyisheading,andhowdeveloperscanbenefit.

The realityaboutbeingaprogrammer is that it’snota job title,oranhonorary titlegiven for graduating with a technical degree. It’s primarily amind-set, which uses thepowerofcomputingtosolvenewandinterestingproblems.Programmerscanbe

Studententrepreneursdesigningthenextsocialnetwork.Accountantsseekingmoreefficientwaystomanageclients’book-keeping.Professionals whowant to helpmake law,medicine or sciencemore interesting andaccessible.Long-termunemployedadultslookingtomakethemostoftheirtime.Socialentrepreneursprovidingcontentmanagementsystemsforcharities,churchesandothercauses.

Teachers, doctors, engineers or builders are all one and the samewhen it comes toprogramming— they are problem solvers.Thekey to success in problem solving is infamiliaritywiththeprinciples,beingawareofthetoolsanddreamingupthepossibilities.

To get themost out of this journey, Iwould recommend skim reading each chapterfirst, and then going over them much more slowly; digesting all the new ideas andknowledge,andfittingthepiecestogether.

Withallofthisinmind,letusgetgoing!

Page 15: Programming a Primer Coding Fo

StartingPoint

Page 16: Programming a Primer Coding Fo

Chapter1

Introduction

Formanyofus,computerprogrammingisanunwelcomethought.Thephraseringsalarmbells, conjuring up ideas of tedious typing, complex concepts and mind-bendingmathematics that are difficult to understand or engage with. These preconceptions canstand between us and one of the greatest tools for progress that humankind has at itsdisposal.AsIhope toshow, therealityofprogrammingisdifferent.Programmingisaninstrument that can be learned by any patient and determined novice who is open tocreatingwithinthemselvesanewtalent.Youdonotneedtospendyears learninghowacomputerworksfromthegroundupbeforeyoucanreachcompetencyinwritingsoftware.Askilledcraftsmandoesnotneedtoknowhowhismachinerywasbuiltinordertobeabletocreatesomethingwithit.Forcomputerprogrammers,programmingisatoolformakingtheirideasareality.

WhatisProgramming?Programming is the process of specifying a set of instructions to be performed by acomputer in order to solve a problem. Programmers use a ‘programming language’ toinstructacomputerhowtobehave.Programming languagesareavocabularyandsetofgrammaticalrulesforinstructingacomputertoperformspecifictasks.Eachlanguagehasa set of keywords and a special syntax for organising computer instructions. Theselanguagesareintendedtobe‘humanreadable’,sopeoplecanwriteprogramswiththem,andmodifytheprogrammesinaccordancewiththeirrequirements.

WhyLearntoProgram?Sowhytakethetimetolearnhowtoprogram?Itisprobablythefirstquestionyouhave,andit’safairone.AsIhopetoshow,thereareagoodnumberofreasonswhyyoushouldlearntoprogram.Iwilltakeyouthroughsomeofthemostsignificant.

First, business and social enterprises are startedwhenaproblem is identified, andasolution is sought. Microsoft and Apple saw the problems involved with manual datastorage, computation and communication, and so developed personal computers.Facebook identified a range of problems associated with poor connections betweenindividualsacrosstheworldandcreatedthesocialmediaplatformweusetoday.LinkedInwasbornin2003whenReidHoffmanetal.soughttoputourbusinessnetworkingonlineinorder to solveproblems regarding finding talent,managingbusiness connections andpresenting one’s professional credentials to potential employers. These are the bighousehold names of the technology industry, but every year tens of thousands ofentrepreneurssolveproblems,createbusinessesandchangetheworldthroughdeliveringnew websites, apps and desktop software to the world. Learn to program to solve big

Page 17: Programming a Primer Coding Fo

problems.

Second,computersareinbillionsofhomes,officesandpocketsacrosstheglobe.Theyarethedevicesweuseeveryday,andthat’snotgoingtochange.Ifyouareareasonablycompetent computer programmer you will never find yourself without a job. You canworkasaself-employedwebdeveloperoramobileapplicationconsultant.Youcanworkfor a company in the technology industry or sell your own indie games. In a growingmarketwithahighdemandforskilledprogrammersyou’llneverbeoutofajobforlong.Learntoprogramforacareer.

Third,allofusenjoydoingthingsthatareskilful.Welearntodance,orplaythepiano,write a journal or spend an afternoon painting a glorious landscape.Many of us enjoycreating, whether it is works of literature or choreography. Programming is a hugelycreativechallenge.Ihaveenjoyedspendingcountlesshoursdesigningbeautifulwebsitesor smartphone apps that have been technically and aesthetically satisfying. That issomethingwhichishugelyrewarding.Learntoprogramforfun.

Thereareahostofotherreasonswhyyoushould learn toprogram.Theremaybeaspecificprojectyoumayhave inmind,oryoucando it as an intellectual challenge,oreven just to show off a new skill to your friends. Whatever your age, parentalresponsibilities, occupation or intellectual ability, programming is an enjoyable,achievable and practical skill allowing the creation of all sorts of applications for thebenefitofyouandothers.

HowdoesaProgramWork?Theprimarypurposeoftheentireengineeringenterpriseistofindwaysofusingnaturallawstocreatethingsthatsolveproblems.Smallandsimplecomponentsaredesignedfromscientific principles, and then combined together to form more complex and powerfulparts, that are then assembled to form systems that simplify the execution of complexoperations.Thisconcept isknownasabstraction.Acamshaftandcrankshaftare simplecomponents,which formpartof anengine,which is itself a significant componentof acar. A car is a complex object with powerful capabilities, yet it can be used withoutknowinghow itworks.Abstractingawaycomplexcomponents ‘under thehood’ ishowwecreatesimpleyetpowerfultoolssuchasthevehiclesweuseeveryday.

Computersarethesame.They’remadeofthousandsofcomponentswhichthemselvesaremulti-part, andwhicharepreciselymanufactured tohaveveryspecific function.Anoperatingsystem(OS)suchasWindows8isanextensionofthisprocess.Ithidesalotofcomplexbehaviour,sotheusercanusethecomputerintuitivelyandeasily.Eachlayerofcomplexityinthedesignofalaptop,forinstance,isalayerofabstractionbuildinguponthecomplexityofthelayersbeforeit.

Generally,acomputerprogramisbestdescribedasoneprimarylayerofabstraction.Ituses the rich features of simple programming languages available to the developer tocreateapowerfulandsimpleexperiencefortheendusertoenjoy.Aprogram,then, isasequenceofinstructionsrunonacomputerinordertoachievesometask.Websites,appsandenterprisesoftwarecanallbedescribedasasequenceofinstructionstobeexecutedby a computer. Typically, they have some kind of input, some kind of processing

Page 18: Programming a Primer Coding Fo

capabilityorfunctionalityand,finally,anoutput.

Togivesomeexamples—agamehasinputfromyourjoystickorkeyboard,performscalculationstoprocessyourmovementsintogameplay,andthenoutputsthegameplayonscreen. An automatic trading agent takes in stock market data, attempts to learn thebehaviour of the stock, and, as an output, predicts the stock’s future price (to varyingdegreesofaccuracy).Perhapsabitclosertohome,awebbrowsertakesaHTMLfileasitsinput, processes it by converting theHTML into a page of text and graphics, and thendisplaysthecontent.

Ineachof theseexamples theprogrammer, throughexplicit instructions,dictates thebehaviourofthesoftware—‘showthispicture’,‘calculatethisequation’,forexample.Ofcoursetheinstructionsaren’tquitethatsimpleandweneedtounderstandexactlyhowwecan tell the computerwhat to do,which iswhatwe’ll look at for the remainder of thischapter.

ProgrammingLanguagesThe English language is a language that only humans can understand. Computers aredesigned to understand a different language. They only respond to 1s and 0s. Everyoperation of a computer can be reduced to this binary behaviour. The role of aprogramming language is to act as a crossover language that can be easily read andunderstood by humans, but can also be translated into 1s and 0s (so called machinelanguage)forthecomputertounderstand.

Acollectionofinstructionsthatachievessomecomputationalgoalformsthebasisofaprogram. These instructions need to be understood by a human and translated intomachinelanguage.The‘humanreadable’codeisknownassourcecode.This is therawfilewrittenbyahumanintheprogramminglanguagetheyareusing,whichwilllaterbetranslatedandusedbythecomputer.

Therearetwocategoriesoflanguages,andtheirnamesdepictthewayinwhichtheyare executed on a computer — compiled and interpreted. Compiled programminglanguagesarethosewhosesourcecodeisfirstwrittenandlatertranslatedintoaseparateexecutablefilebyacompiler.Thecompilerturnsthesourcecodeintothemachinecodethat can be directly run on the computer. Examples of some popular compiledprogramming languages includeC,C++ (‘C-plus-plus’) andC# (‘C-sharp’). Interpretedlanguages,suchasPython,JavaScriptandRuby,arethoseforwhomtheexecutablefileisthesameasthesourcecodefile.Thatis,thefilecontainingthesourcecodeisexecutedbyan interpreter, which translates the source code into executable code at themoment ofexecution.Thisremovestheneedforcompiling.

Everyprogramminglanguagehasitsownbenefitsanddrawbacksforeachapplication.Each language is designed for a specific kind of use and each behaves in a slightlydifferentway.Therearegeneral ideas thataresharedacrossdifferent languages,but thebehaviour,lookandfeelofeachlanguageisdifferent.

An important characteristic of a programming language, which you will eventuallylearntoidentifywhenlookingatdifferentlanguages,istheextenttowhichalanguageisseparated in its behaviour from the underlying behaviour of the processor. This is the

Page 19: Programming a Primer Coding Fo

concept of abstraction that we’ve already come across — separating functionality orbehaviourfromthedetailsabouthowsomethingworks.

Programminglanguagesareabstractedfromthedetailofthebinaryoperationsofthecomputer inmachine language todifferent extents.Eachprogramming language canbeplacedonascalefromlow-levellanguages(lowornolevelofabstractionfrommachinelanguage) to high-level languages (strong abstraction). Low-level languages such asAssembly, C and C++ are bare-metal languages, which provide low abstraction.Assembler simply translates thebinaryofmachine language intonamedcommandsandlabels.CandC++providemoreabstractionbutarenowadaysconsideredfairlylow-levellanguages.High-levellanguagesincludeJavaScript,C#andinterpretedlanguages,whichare typically easier for humans to read, and often automate or hide difficult aspects ofprogramming.

LanguagesfortheWebThe languages mentioned so far are most commonly used to develop software for thedesktoporformobiledevices.Webtechnologyisahugelyimportantaspectofcomputerscience and is later explained inmuch greater depth, itwill be useful to introduce youbrieflytoprogramminglanguagesfortheweb.

Web-basedapplicationssuchassocialmediasites,newssites,entertainmentplatformsandotheronline toolscan typicallybedivided into threeparts—databases, server-sidesoftwareandclientsidesoftware.Eachof these threepartsaremostcommonlyoperatedusingseparatelanguages,althoughitispossibletouseasinglelanguageforeveryaspect.Databases are often accessed using SQL, which is a high-level database queryinglanguage.Server-sidesoftware,whichmanagesthesedatabasesandthedatathatissenttotheclient (user),areusuallywritten inPHP,RubyorPython(all interpreted languages).Client-sidelanguagesarethosethatmakeupthepagesthataresenttoandexecutedontheuser’s computer when a web page is received. The most common language here isJavaScript, which provides basic interactivity and animation on the page. This is inaddition toCSS (for page formatting) andHTML,which is amark-up languagewhichspecifieshowtheelementsofawebpageshouldappear,andhowtheyshouldfittogether.

Aswehavejustseen,therearenumerousprogramminglanguagesoutthere;eachofthem suited to particular tasks. In order to write a programwe’ll need to knowwhichprogramminglanguage touse tosuit thegoal.Nowwe’vegotabroadunderstandingofwhataprogramminglanguageis,andwhatlanguagesareoutthere,letuslookatthetoolswewillneedtogetcoding.

WhatDoINeed?Inordertotellthecomputerwhattodo,weneedafewthings.First,weneedatexteditorinordertowriteourcode.AcommontexteditorlikeNotepadorMicrosoftWordwouldbe sufficient, but they’re not particularly built forwriting code in.MicrosoftWindowsusers should use something like ‘Programmers Notepad’1 or ‘Notepad++’2, which aresimple to find, install and use.Mac users can find TextWrangler3 for free on the AppStore, but plenty of others are out there. The only purpose of a text editor for

Page 20: Programming a Primer Coding Fo

programmingistoenableustocreate,editandsavetextfileswhichwillstoreourcode.

Second,inordertoturnyourcodeintoanexecutablefile,we’llneedacompileroraninterpreter,whichyou’vejustlearnedabout.Dependingonthelanguagebeingused,thiswill either allow you to run your code as it is (interpret), or translate it (compile) intomachinecodethatcanberunwithoutaninterpreter.OneexampleisPython—ifyouneedhelp installingyourPython interpreteror findinganappropriate text editor,havea readthroughAppendixA—PythonDevelopmentEnvironment.

Third,youneedabasicunderstandingoftherelevantprogramminglanguage,whichisthepurposeofthisbook.

HowtoWriteaProgramAshasalreadybeenmentioned,theabilitytouseaprogramminglanguageismerelythetoolusedbyaprogrammer to solveproblems.Agoodprogrammer isnotdifferentiatedfromapoorprogrammerbythenumberoflanguagestheyknow,inthesamewaythatitisnotmerelytheabilityofacarpentertouseawiderangeoftoolsthatmakeshimtalentedatwhathedoes.We’llnowlookatageneralisedprocessofdevelopingaprogramthatwillhelpyouunderstandhowtousethetoolsforcreatinghigh-qualitysoftware.

TheProcessIn the development of a computer program, the programmer undertakes a sequence ofsteps, which develop the program from start to finish. It is helpful to think of adevelopmentprocessasbeingcomprisedofasequenceofactivities.Theseactivitiesare:

Planning,Implementation,testinganddocumentation,Deploymentandmaintenance.

In situations where there are several programmers working on the same project, arangeofdevelopmentmodelsareavailable tobeused,yet forsingle-developerprojects,eachoftheseactivitiesareessentialandtherearesomegeneralremarkstomakeoneach.

Planning is the most essential part of the development process to ensure that theprogramwillbemanageable,scalable,efficientandasquicktoupdateaspossible.Spendmoretimeplanningandyou’llsavemoretimelateron.

Planningshouldbedonefromageneralleveltoamoredetailedone.Thismeans,firstand foremost, identifying the requirements of the project. Whether it is an employer,customeroryouwho theproject is for, theywill typicallyhave some ideaofhow theywanttheendproducttolook,butnotfullyunderstandhowitneedstobedesigned.You’llneed to learn how to identify incomplete or ambiguous requirements and ask forclarification.

Once the requirements are defined, it’s the developer’s task to plan the technical

Page 21: Programming a Primer Coding Fo

design of the program.You need to consider which programming language to use, thestructureofyourcode,andwhereyoucansavetimebyusinganyavailableworkofthirdparties.Youalsoneedtocontinuallyre-evaluateyourdesigntoensureithasthecapacitytofullymeettherequirementsoftheproject.

Implementation, testing and documentation is themeat of the development process.Hereyou’llactuallyprogramthecodeforyourproject,whilecontinuallyverifyingthatitsbehaviouriscorrect.Errorsareeasiertofindandfixassoonasthey’vebeenwritten,notdayslater;sotestingisimportantateachstageofimplementation.

Most development projects can result in relatively large collections of source code(codebases), and remembering how parts of it work or why you made certain designdecisions can be challenging. This is where documentation comes in. Use a separatesimpletextdocumentandcommentsinyourcode(explainedinthenextchapter)toclarifydesigndecisionsandtoexplainwhatyouhavecoded.Thiswillmakeiteasiertomanagelargeamountsofsourcecodeanddesignefficiently.

Deployment andmaintenance start as soon as the project has been completed andadequatelytested.Thiswillincludeinstallation,customisation,verificationandaperiodofevaluation by the user. Straight after deployment, developers need to be prepared forcriticismandmusthavetheabilitytofixbugs(errors)quickly.Maintainingandenhancinglargeprogramscanbetimeconsumingasnewfaultsarefoundornewfeaturesareadded.

Theseactivitiesarelikelytoappeardauntingtobeginners.Myexpectationisnotthatyouwillcompletelyunderstandthedevelopmentprocessatthisstage,butthathavingthisbirds-eye overview of the process will help you understand where the programmingprinciplesandknowledgethatyoulearnlaterfitintothecompletepicture.

Nowyouknowabitaboutwhyprogrammingisimportanttolearn,whatprogrammingisandtheprocess thatcomputerprogrammersusetoreleaseapieceofsoftware,you’rereadytolearnthebuildingblocksofaprogram.

Questions1. Howisaprogramminglanguagebestdefined?2. Whatismeantbytheideaofabstraction?3. Whatismachinelanguage?4. Whatisthedifferencebetweenacompiledandaninterpretedlanguage?5. Whatarethethreebasictoolsyouneedinordertotellacomputerwhattodo?6. Whatarethethreemainactivitiesyouneedtocarryoutinordertodevelopapieceof

software?

1http://www.pnotepad.org/2http://notepad-plus-plus.org/3http://www.barebones.com/products/textwrangler/download.html

Page 22: Programming a Primer Coding Fo

BuildingBlocks

Page 23: Programming a Primer Coding Fo

Chapter2

VariablesandBasicOperations

Thebasicprinciplesandconcepts incomputerprogrammingare thebuildingblocks forcreatingpowerfulandinnovativeapplications.Pythonisaverystraightforwardlanguageandhasasimplesyntax.Itwillbethelanguagewewillusetoillustratetheconceptsthatwe pick up along the way. It is designed to allow programmers to create powerful,beautiful code, quickly and enjoyably. You will be able to run the brief examples foryourselfusingyourtexteditorandPythoninterpreter,tochecktheywork.Thebestwaytousethisbookistoreadachapter,thenruneachoftheexampleprogramsinthatchapteronyourowncomputer.Trychangingthecodeabittogetafeelforhowyoucantellthecomputerwhat todo. Ifyouhadprefernot toworryyetaboutgettingyourownPythoninterpreter installed, repl. it1 has a really neat online Python text editor and interpreterreadyforyoutousestraightaway.

IfyouareusingyourownPythoninterpreteryouhavetwooptions:

Inputthe.pyfileintoyourPythoninterpreterTurnyour.pyfileintoanexecutablefile

The first option is executed, using your command line (or terminal on a Mac), asfollows:$pythonmy_file.p

ThesecondappliesonlytoMacandLinuxusersandrequiresyoutoappendyour.pyfilewiththepathtoyourPythoninterpreter.JustaddthefollowinglinetothetopofyourPythonsourcecodetotellyourcomputerthatyou’vewrittenPythoncode,soyouwanttoexecuteitusingyourPythoninterpreter.#!/usr/bin/python

PlacethisatthetopofeachPythoncodefileyourun.Thismeansyoucanexecutethecodewithoutneedingtoloaditintoyourinterpreterwhenyourunit.

Ifyou’reusingrepl.it,youdon’tneedtoworryaboutthis.Youcanexecuteaprogramappended as such using the command belowwhere ‘my_file.py’ is replaced with yourcode’sfilename.$./my_file.py

The./heremeansthat thefile isfoundinyourcurrentdirectory(thefolder thatyouare currently using). Alternatively you can simply double-click on the program fromwithinyourfileexplorer.

Page 24: Programming a Primer Coding Fo

Ifyou’reusingPythononaWindowsmachine,youwilljustneedtodoubleclickonthesourcecodefiletorunitusingyourPythoninterpreter.

A‘HelloWorld’fromPythonOneofthemostbasicprogramsthatbewrittenistheage-old‘HelloWorld’program,soitseemsonlyfittingthatthischaptershouldbeginwithPython’s‘HelloWorld’.Toprintalineoftexttothescreen,justwrite:print‘HelloWorld’

Theoutputofthisprogramshouldlooklikethis:$HelloWorld

Here,the$symbolisusedtodenotetheoutputoftheprogram.Ifyou’reusingrepl.it,thiswillappearas‘⇒’followedbytheoutput.

VariablesEverymobileapplication,website,desktopsoftwareorembeddedsystemcanbethoughtofasbeingaprogramthatworkswithdata,whetheritisasimpleversionprinting‘HelloWorld’toascreen,oraverycomplexversioncollectingdatafromsatellite imagingandprocessingittopredicttheweather.Evenagame,whichmaynotcollectdatainanywayfrom the realworld,operatesbyperformingmillionsofcalculationsper secondondatainsidetheprogram.

Datathatisacceptedbyaprogramasaninputisstoredinmemory,atauniqueaddresssothatitcanbeeasilyreadorchanged.Ifprogrammershadtorememberthelocationsofallofthesevariablesinmemory,theprocessofprogrammingwouldbeimmenselytediousanddifficult.Happily,inthemainprogramminglanguagethatwe’llbelookingat,andinmost others, the programmer does not need to worry about the address where data isstored.Instead,programminglanguagesallowustorefertodatabyaname.Itemsofdata,whicharestoredinmemoryandreferredtobyname,arecalledvariables.

Variablesareused inprograms to store inputteddata andcalculations thatuseothervariables.Thevariablescanstoredifferenttypesofdata.Ingeneral,variablesaredeclared(created)inthreesteps:

1. Assigneachvariableauniqueanddescriptivename2. Specifythetypeofdatathevariablecanhold3. Assignavaluetoeachvariable(numbersorletters)

InPython,wedonotalwaysneed todeclarevariablesbeforeusing them,ordeclaretheirtype.Forexample,wecandeclareavariableasfollows:myInteger=3

Pythonsupportstwoprimarytypesofnumbers—integersandfloatingpointnumbers.The above example is a definition of an integer and we have chosen its name to be

Page 25: Programming a Primer Coding Fo

descriptive of what it is. To define a floating point number, we can use either of thefollowingnotations:

(The#symbolisusedinPythonforcomments.ThismeansthattheinterpreterignoresanythingafterthatsymbolonalineinaPythonprogram.Thisallowsustowritehelpfulcommentsnexttoourcodetoexplainwhat’sgoingon.)

Inprogramming,wordsorsentencesstoredinavariablearecalledstrings.Theycanstore any text that youmay need in your program.Strings are defined in Python usingeithersingleordoublequotationmarks:

Inordertoincludeactualquotationmarksinsideyourstringwithoutthemterminatingthe string, you can use a backslash (\) before the quotationmark.Alternatively, if yourstring is encapsulatedwith single quotes, you can use double quotes inside your stringwithoutneedingtouseabackslash:

Inadditiontostringsandintegersandfloatingpointnumbers,acommonandhugelyusefultypeofvariableinPythonisthelist.Alistisacollectionofothervariablesofanydata typeandofany length.A list issimilar toanarray inother languages,but ismoreflexible.Alistisfirstdeclared,andthenpopulatedasfollows:

Listscanalsobedeclaredandpopulatedinonestep,in-line:

Thefinalimportantvariablethatwe’regoingtolookatisthePythondictionaryobject.Adictionaryisanobjectwhichmatchesakeywithavalue.Itisakindoflistbutelementsareaccessednotbyitsindex,butbyakey.

Page 26: Programming a Primer Coding Fo

Take the example of a phonebook as in the example above.Herewe have a name,matched up with a phone number. When we print the element in the dictionary‘phonebook’withthekey‘James’, thedictionarylocatesthevaluecorrespondingtothatkeyandprintsJames’sphonenumber.

Dictionaries areuseful for storingawide rangeofdata inmanydifferent situations,suchasmatchingwordstodefinitions,matchingnamestophonenumbersormatchingcarregistrationnumberstomakesandmodels.

BasicOperationsCommon number-crunching programs are spreadsheets, database software and games.Stringmanipulationisperformedonsocialmediawebsites,wordprocessorsandlanguagetranslators.Whenprogramming, thesekindofmanipulationsaregenerallyreferred toasoperations.Thesearesimpleprocessesthatdataundergoesinordertoformpartofsomekindofcomputation.

Somesimpleoperationsareperformedonstringsandnumbersintheseprograms,andarebuiltuptoformcomplexequationsorsetsofpowerfulinstructions.

Basicmathematicaloperationscanbeperformedonnumbers:

Above,wehavesurroundedthevariables‘firstInt’and‘secondInt’withbracketsandused theword ‘float’ before them. This casts the integers as floating point numbers inorderthatwecanperformdivisiononthem.

Apower operation is onewhichmultiplies a number by itself a certain number oftimes.Forexample23is8(2×2×2).Inordertoperformapoweroperation,wecanusetwomultiplicationsymbols:

Page 27: Programming a Primer Coding Fo

Anotheroperatorwhichmaybeunfamiliartoyouisthemodulo(%)operator,whichreturnstheintegerremainderofadivision.

Inadditiontonumericaloperatorsbeingusedtoperformcalculations,Pythonprovidesexcellent features for stringmanipulationwhich form new strings, as illustrated by thefollowingexample:

Herewehaveaddedtwoexplicitlydeclaredstringstogether—greetingandname—withan implicitstring in themiddle (“,“).Theprocessofaddingstrings in thisway toformnewstringiscalledconcatenation.

TryingtoconcatenatenumberswithinstringsinPythonwillnotwork:

TheoutputofthisprogramisaPythonerrorwhichtellsusthattheoperator‘+’doesnot support operands of type ‘int’ and ‘str’ (string) together. However, we can cast anintegertoastringwithoutneedingtodeclareanewvariable:

Thefunction(functionswillbeexplainedlater)str()canbeusedtoconvertanintegeror floating point number to a string on the fly, so thatwe can print numbers alongsidestringsusingconcatenation.

Themultiplicationoperator(*)canbeusedwithastringandanumberaswellastwonumbersandbehavesbyrepeatingthestringbythevalueofthenumber:

Wecanalsousetheincrement‘+=’anddecrement‘–=’operatorstoaddaspecifiedvalue to a number variable. These operators add or subtract their operand to a numberrespectively.Forexample:

Page 28: Programming a Primer Coding Fo

Theseareparticularlyusefulforperformingbasicmathematicalcalculationsondatainaprogramandyou’llusethemoften.

InputandOutputSoftware is useless unless it does somethingwith the data it has processed. This oftenmeansthatdataiscollectedinsomeway,processedandthendisplayedtotheuser.Forthetime being, our use of Pythons Input and Output (I/O) features will be primarily forlearning to use the language and process data, but at a later stage we will use text ornumericalinputandtext-orgraphics-basedoutputs.

Aswe’vealreadyseentooutputastringtothecommandlineinPython,weuse:print‘thisissometext’

Howeverthisonlygivesusalimitedcapability.Whataboutifwewanttoprintlotsofdifferent variables in the same line?Python allowsus to addplaceholders for variablesinsidethemainstringtobeprintedandthenspecifythevariablesattheend.Forexample:

Inthisexample,%sdepictstheplaceholderforastringand%dspecifiesthelocationforanumber.Thevariablesarethenlistedintheorderinwhichtheyshouldappear,insidethebrackets,separatedfromthestringbya%symbol.Thistechniquecanbeextendedtoincludeanynumberofvariablesinsideastringtobeprinted.

Allsoftwareacceptssomekindofinput,whetheritisfromasensor,theInternetorahuman.When learning to write programs andwhen designing them professionally, it’simportant,therefore,tounderstandhowtogetbasicinputfromauser.

Pythonhereoffersustheinput()functionallowingustoasktheuserforsomekindofinformationandtocollecttheirreply.

Bydefault, the stringenteredby theuserwill alwaysbea string. Ifyou require theusertoenteranumber,suchastheirage,you’llneedtoconverttheirentryintoanumberasfollows:

Page 29: Programming a Primer Coding Fo

Wenowhave thebasic skills required toaccept,processandoutputbasicuserdata,butwe’veonlylookedatperformingbasiccalculationsandstringmanipulationsofar.Inorder to make our programs more interesting and powerful, we need to introduce theability toperformrepeated tasksandmake intelligentdecisionsbasedupon thedatawehave.

Questions1. Howdoesthedatatypeintegerdifferfromafloatingpointnumber?2. Shouldthevalueofastringbedeclaredinsinglequotesordoublequoteswhenitisset?3. HowdoesthelistdatatypedifferfromthedictionarydatatypeinPython?4. Whatsymbolmustyouuseinordertoperforma‘tothepowerof’operationinPython?

Writedownaprogramwhichprintsthevalueof3tothepowerof7.5. Whatdotheincrementanddecrementoperatorsdo?6. Whenoutputtingastringtothescreen,what’sthedifferencebetweentheplaceholders

%dand%s?

1http://repl.it/UL8/languages/Python

Page 30: Programming a Primer Coding Fo

Chapter3

DecisionsandLoops

OneofthevariablesthatweleftoutinChapter2,wastheBooleanvariable,orbool forshort.Thisisavariablethatcanhaveonlytwopossiblevalues—trueorfalse.

We’veseen thatanumbervariablecanbeassignedavaluebasedupon thevalueofpreviouslydeclaredvariables,forexample,z=x+y.Thisexampleevaluatesthesumofxandy and assigns it to z.The same canbe donewithBooleans—we can evaluate anexpressionthatcaneitherbetrueorfalse,andassigntheresulttoaBooleanvariable.

ConditionsAconditionissomethingthatcanbeevaluatedastrueorfalse,dependingonthevaluesofthe variables, and the symbols used in the condition’s expression. The followingdemonstratestheequalitycondition(==),whichistrueiftheoperandsareequalinvalue.

Theoperand‘!=’isequivalentto‘notequal’andistrueiftheoperandsarenotequaltoeachother.

Variablescanbecomparedtoeachotherinsizeusingtheinequalityoperators<(‘lessthan’),>(‘greaterthan’),<=(‘lessthanorequalto’)or>=(‘greaterthanorequalto’).

If the Boolean expression requires several conditions to be met it can include thekeywords‘and’and‘or’.Forexample:

Page 31: Programming a Primer Coding Fo

The‘and’keywordrequiresbothexpressionstobemet,butthe‘or’keywordrequireseitherexpressiontobemetinorderforthewholeconditiontobetrue.

ToinvertaBooleanoutput,the‘not’keywordcanbeused.Forexample:

Thefinalkeywordthatweneedtolookatisthe‘in’keyword.ThisoperatorisusedtocheckifagivenvalueisfoundinaPythonlist.WesawinChapter2howtocreateandappendliststocontainlotsofitemsofdata.The‘in’keywordlooksatalistofelements,and is ‘true’ if the list contains a value equal to the operand. The following exampleillustrateshowthisworks:

The‘if’StatementThe next aspect of programming that we will look at is decision making. In humanlanguage we make decisions by comparing the different options available to us, andchoosingwhichweprefer.Forinstance,if thesunisclearandtheairiswarm,thenjustwearaT-shirt.Orelse,iftheskyisclearbuttheairiscold,thenwearajumper.Orelse,iftheskyisnotclear,buttheairiswarmwearacoat.Orelse,iftheskyisnotclearandtheairiscold,wearacoatandajumper.

Although for humans this is often a subconscious routine, computers use a similarprocessofworkingthroughsetsofpredefinedlogicalprocessesinordertomakedecisionsandgetthingsdone.

Inhumanlanguageweusetheword‘if’whenexplainingourdecisionmaking.Pythonuses the same keyword if. If a Boolean expression— a condition that evaluates as aBoolean—istrue,Pythonexecutesacertainblockofcode.If it isnot true(inBooleanelse),anotherblockofcodemaybeexecuted.

Page 32: Programming a Primer Coding Fo

Thediagramabovemakesthisclear.Itdemonstratestheflowoflogicforasimple‘if’statementwithno‘else’clause.LetushavealookatthebasicsyntaxinPython:

Putintowords,thisisreadas‘ifthefirstconditionistrue,executethefirstblockofcode,elseif(‘elif’)thesecondconditionistrue,executethesecondblockofcode,else(inallothercircumstances)executethethirdblockofcode’.Ifthefirstconditionismet,thefirstblockofcodeisexecuted,andthelasttwoareignored.Ifthefirstconditionisnotmetbut thesecondcondition is, thesecondblockofcode isexecutedand the third ignored.Onlyifneitherconditionismet,willthethirdblockofcodebeexecuted.

AtthisstageitwillbehelpfultoexplainindentationandblocksinPython.Ablockofcodeisasequenceofinstructionsthatareexecutedatacertainpointinaprogram.Thismay be some set of instructions inside an ‘if’ statement, or inside a loop, aswe’ll seeshortly.Pythonseparatesblocksofcodefromeachotherusingindentation.

Page 33: Programming a Primer Coding Fo

Asyoucan see in the example above, two ‘print’ commandsare indented to ensuretheyareunderstoodbytheinterpreterasablockofcodetobeexecutedifandonlyifthecondition ismet. Lines of code can be indented in Python using theTABkey on yourkeyboard,orbyentering4spaces.IndentationisveryimportantinPython.Ifyourcodeisnotcorrectlyindented,itwillnotbecorrectlyinterpreted.Donotworrytoomuchatthisstageaboutwhen to indentyour code, asyouwill soonget a feel for itwhenyou readsomemoreexamplesinlaterchapters.

The‘if’statementcanbeusedseparatelyfrom‘elif’or‘else’incaseswhereasingleconditionneedstobetestedandthereisonlyoneblockofcodeforthatsinglecondition.Thustheusercanuse‘if’asintheindentationexampleabove.

However,iftheproblemyouaretryingtosolverequiresoneoftwoactionsdependingonapairofconditions,youcanuse‘if’and‘elif’withoutusing‘else’,asinthisexample:

Alternatively,‘if’and‘else’canbeusedwhenasingleconditionrequirestestingandsomeactionisrequiredifit’snotmet:

Asyouwillhavenoticed,whenapriorexpressionismet,theremainingexpressionsinthe ‘if…else’ block are not tested, since the block corresponding to the first satisfiedcondition is executed. If multiple blocks need to be executed for different conditions,multiple‘if…else’statementscanbeused.

Page 34: Programming a Primer Coding Fo

The‘for’LoopInadditiontotheabove‘evaluatingconditions’,oneofthemostcommonlyusedconceptsinprogrammingistheloop.Thisisacommandforwhentasksneedtoberepeatedseveraltimes.Forexample,youmayhavealistofnames(asabove)andneedtoprintoutalistofallthenamesinthelist.Insteadofmanuallytypingoutcommandstoseparatelyprinteachelement of the list, you can use a loop to iterate over the list, and perform the printcommandoneachelement.Thus,wecanreplacethefollowing:

withanoperationallyidenticalblock,usinga‘for’loop.

In this example, we have only saved one line of text, but for larger lists we can

Page 35: Programming a Primer Coding Fo

performoperationsmuchfasterusingloops.

Theflowoflogicisillustratedinthediagrambelow.

So,acounterisdefinedandtheloop’sconditionistested.Iftheconditionissatisfied,the contained block of code is executed and the counter is incremented. Unlike mostprograming languages, Python hides the incrementing for us. The keyword ‘in’ causesPythontoautomaticallyiterateovertherangespecifiedbyincrementingacounter.

Theaboveexampleusesthe‘for<iterator>in<list>:’syntaxwhich ishelpfulwhenwedon’tknowthelengthofalist.However,wecanalsousetheoperator‘for’toloopoverablockaspecificnumberoftimes.Forinstance,toprintconsecutivenumberstothescreen,wecandothefollowing:

InPython—andinmostotherprogramminglanguages—lists(includinga‘range’ina ‘for’ loop) begin with the “0th” element. So the above example performs a loop ofincreasing‘x’fromx=θtox=4,thereforerunningfivetimesasspecified.

Page 36: Programming a Primer Coding Fo

Wecanalso ‘nest’ loops insideother loops inorder toexecuteacertain functiononeachiteration(inthiscase,aniterationisonecycleoftheloop)oftheouterloop.

Here, theouter loop takes thenumbervariablex fromx=θ tox=2, and for eachvalueofx,thenumbervariableyhasfirstthevaluey=θ,thenthevaluey=1,sincetheinnerlooptakesthevariablefromy=θtoy=1.

The‘while’LoopThe‘while’loopissimilartothe‘for’loop,exceptthatthedurationofitsloopingisnotalwayspredefinedbeforetheloopbegins.The‘while’loopcontinuestoloopforaslongasitsconditionisevaluatedastrue,asshownintheillustrationbelow:

ThebasicsyntaxforthePython‘while’loopis:

The expression here can be anythingwe have seen previouslywhich evaluates to aBoolean.Iftheexpressionisfalse,theloopisendedandtheprogram’sexecutionresumeswith thenext instruction after theblock inside the ‘while’ loop.The followingexampleillustratesthisbehaviour:

Page 37: Programming a Primer Coding Fo

Heretheloopisresumeduntiltheuserenters‘James’astheirname,since,whentheydo,theconditionofthe‘while’loopisnolongersatisfied,sotheloopisbroken.

TheKeywords‘break’and‘continue’Whenusing‘for’and/or‘while’loopsinPython,youmaywanttoexitaparticularloopifa certain event occurs, or a certain condition is met that is different from the loop’scondition.Alternatively,youmayneedtherestofthecurrentblockinalooptobeskippedandthenextlooptobegin.

The Python ‘break’ keyword quits the loop in which it is found. The ‘continue’keywordstopsexecutingtherestoftheblockinsidealoopinwhichthekeywordisfound,andresumesfromthebeginningoftheloopatthenextcycle.Thus:

Intheexampleabove,thevariablecountisincrementedby1,usingtheoperator‘+=’.Witheachcycleoftheloopthevariablecountistestedtoseeifitisbiggerthan5.Ifitis,theloopbreaks,andtheprogramexits.

Page 38: Programming a Primer Coding Fo

In this‘for’ loop, theremainderoperator%calculates theremainderafterdividingxwith 2. If the remainder is 1, x is odd, the expression resolves to false and the loopproceedstocompletebyprintingx.Iftheremainderis0,xisevenandtheloopcontinues,skippingthe‘printx’instruction.

Questions1. WhichBooleanvaluewouldthefollowingexpressionevaluateto:((4=<2)and(True

!=False))?

2. Whatdoesthe‘in’operatordo?3. Writeasmallprogramwhichaskstheuserfortheirage,andiftheirageis17orgreater,

printsthestring“Youareoldenoughtodrive”,otherwiseitprints“Youaretooyoungtodrive”.

4. Inthecontextofa‘while’loop,whatdothe‘break’and‘continue’keywordsdo?

Page 39: Programming a Primer Coding Fo

Chapter4

Functions

So far, we have looked at the basic components of a computer program, includingvariables,operations,conditionalsandloops.Thesearethefoundationofanyprogramyouwillwrite.However, each programwe’vewritten so far has only a single linear set ofinstructions,afterwhichtheprogramfinished.Itistimetointroducefunctions.

Functions are fundamental to computer programs.They are away of dividing codeintoblocksthatcanbereusedwhenneeded.Functionsallowcodetobemoremanageable,morereadableandmorepowerfulinitscapabilities.

InChapter1,weexplored thenotionofabstractionandsaw that itallowsengineersandcomputer scientists tohide trivial low-levelcomputationsaway inorder toprovide,more simply, powerful capabilities to higher-level aspects of a system. In softwaredevelopment‘functions’aretheprimarymeansofabstraction.

Inafunction,apredefinedsetofinstructionsarespecifiedwhicharetobeperformedeachtimethefunctionis‘called’.The‘calling’ofafunctioncanbethoughtofasonepartof your code, requesting that the code inside that function be executed. Typically afunctionwillhaveaninput,anoperationandanoutput,andinthissenseitisequivalenttoamini-orsub-program.Theinputstoafunctionaretypicallyreferredtoasparametersorarguments.TheseparameterscanbeanykindofdatarepresentedasPythonvariablessuchasBooleans,numbers,strings, lists,dictionaries,objects(whichwewillcoverlater)andothers.Theyarepassedintothefunctionwhenitiscalled.Theoperationofafunctionisspecifiedasasetofinstructionswhichmayperformoperationsontheinputs,orotherwisemaymanipulatedataheldoutsideofthefunctionandnotgivenasparameters.Theoutputofafunctionisknownasthefunction’sreturnvalue.Thisisavaluewhichisspecifiedasaresultoftheoperationofthefunctionandisassignedtoavariablewhenthefunctioniscalled.

ThefollowingexampleillustratesthebasicsyntaxfordefiningandexecutingaPythonfunction:

Page 40: Programming a Primer Coding Fo

This may look a bit daunting at first, but Python functions are a very simple andintuitive construct.Thekeyword ‘def’ stands for definition anddenotes a function.Thenextwordistheuser-definednameforthefunction.Thebracketsimmediatelyfollowingthefunctionnamecontainalistofparameternames.Theoperationofthefunctionisthenspecified,andavariableisreturned.

The function is called outside the definition of the function and is given someparametersasinputs.Thefunction’sreturnvalueisassignedtothevariable‘output’andisthenprintedtothescreen.Itisimportanttonotethatafunctionisnotexecutedatthepointinthecodeatwhichitisdefined.Afunctionisonlyexecutedwhenitiscalled.

Functions are not required to accept parameters or output a return value, or evenperformanymeaningfulcomputationas theiroperation.Letus look, for instance,at thefollowingexampleofabasicfunctioninPython:

Thisexampleacceptsnoparametersandsodoesnothaveapairofbracketsafteritsname.Rather, the only operation of this function is to print a string to the screen. Thefunction is defined in line one, and the indented block of code shows that it simplyexecutesone‘print’command.Neitherdoesithaveareturnvalue,soitdoesnotusethePythonkeyword‘return’.Thefunctioniscalledinlinethreeatwhichpointitisexecutedandtheoutputdisplaysthestringprintedtothescreen.

The greeting frommy_function in the example abovewas a little impersonal.Thenextexampledemonstratestheuseofparametersasinputstothefunction.

Page 41: Programming a Primer Coding Fo

Theuseof theparameter insidethefunctionshouldbeclear.Thefunctiondefinitioncalls the input parameter ‘name’ and inserts it into a more personal greeting from outfunction.Outside the functiondefinition, theuser isasked for theirnameand thestringtheyenterisstoredinthevariable‘myName’.Ournewfunction‘my_personal_functon’iscalled, and the user’s name is pasted in. The function then executes, and prints thepersonalgreetingtothescreen.

Nowwe’vemastered the concept of an input parameter let’s go for amathematicalexample,andwriteabasicsummingfunctionwithareturnvalue.

Notethattherearethreepreviouslyunseenfeaturestothisexample.First,ourfunctionaccepts twoparameters insteadof justone. InPythonanynumberofparameterscanbepassedintoafunctionwhenitiscalled,aslongasthenumberofparameterspassedintothefunctionmatchestheamountthefunctionisexpecting.Second,ourinputparametersare specified in the same line as the function is called, instead of being specifiedpreviously by being assigned to a variable. Third, this example returns a value— thenumerical sumof the twoparameters.When the function returns after being called, thenextlineofcodeprintsthevariable‘returnValue’tothescreen,whichhasavalueequalto‘sum’insidethefunction,sinceitisassignedthereturnvalue.

Youmayhavenoticed that inour last function‘sum_two_numbers’,wedidperformsome degree of abstraction. We took two operations — addition and printing — andabstractedthemawayintoafunctionwhichcanbecalledrepeatedlywithasingleline:

Page 42: Programming a Primer Coding Fo

Havingpreviouslydefinedthisfunction,weareabletorunthethreelinesofcodeintheboxabove, toperform the additionandprintingof threedifferentpairsofnumbers.Youcanseethatformorecomplexnumericaloperations,thisconceptofabstractionusingfunctionscanbeextremelypowerful.

ABiggerandBetterExampleNow is a good time for our knowledge of functions to be combinedwithwhatwe

know already about variables and conditions.We’re going to design a function whichperformsarangeofcalculationsontwoinputvariables;thatis,wearegoingtodesignacalculator.

Foraprogrammer, theability to think ina top-down sense isvitally important.Thismeansthatyoumustbeabletounderstandwhatyourprimarygoalisandwhatlower-leveloperationsneedtobeabstractedawayasfunctionsinordertomeetyourrequirements.

So,ourgoalistobuildafunctionwhichacceptsthreeparameters—twonumbersandastring—andperformsthecorrectcalculationonthesenumbersdependingonthevalueofthestring.Thinkinginourtop-downway,wecanseethatourprimaryrequirementisafunctionwiththefollowingform:

To be a calculator, our programmust perform addition, subtraction, multiplication,divisionandpoweroperations.Theoperationofthecalculatordependsonthevalueoftheparameter ‘operation’. From this information about our goal,we’re able to deduce thatinside the ‘calculator’ function,weneed tomakesomekindofdecisionbasedupon thevalueofthestring‘operation’.

Therefore,without specifying the exactoperationsof the functions ‘add’, ‘subtract’,‘multiply’, ‘divide’or ‘power’,weknowthatour ‘calculator’ functionmust takea formsimilartotheonebelow.

Page 43: Programming a Primer Coding Fo

Herethevalueoftheparameter‘operation’istested.Avariable‘result’isassignedthereturnvalueofoneofthe—asyetundefined—functions,determinedbytheoperationtobeperformed.Wecansimplydefinethesefunctionsasthefollowing:

All of these functions take the two number variables ‘a’ and ‘b’ as their inputparametersandreturnavalue.Thefirstfourshouldbeself-explanatorytoyou,howeverthelastmaynotbe.Thefunction‘power’isrequiredtoreturnthevalueof‘a’tothepowerof ‘b’. In other words it should return ‘a’ multiplied by itself ‘b’ times. This isimplementedusingaloopwhich—aftersetting‘result’equalto‘a’—multiplies‘a’by‘result’‘b’times.Then,whentheloopfinishes,thevalueof‘result’isreturned.

Wecannowcombineallthesefunctiondefinitionstogetherintoasinglefile,inordertocompleteourcalculator.

Page 44: Programming a Primer Coding Fo

Herewe’vesimplyplacedallourpreviouslydefinedfunctions intoasinglefile,andcalled the ‘calculator’ function five times, todemonstrateeachmodeofoperation.Witheach‘print’command,we’reprintingtheexplanationofthecalculation,concatenatedwith

Page 45: Programming a Primer Coding Fo

thereturnvalueofthecalculator,convertedtoastringusing‘str’.

Youwill now recognise ‘str( )’ as a function. Each timewe have called ‘str( )’ or,previously,‘int()’,weareusingfunctionsthatarepredefinedforus.Theyarefunctionswhich accept a parameter and return, respectively, the ‘string value’ or ‘integer value’representationof the inputparameter,byperforminganoperationon it.Asweprogressthroughfuturechaptersofthisbookwewillusemanydifferentfunctions,someofwhichwe’llwrite,othersofwhicharebuiltintothePythoninterpreter,andstillotherswewillimportfrom‘libraries’.

One of the powerful things that a function provides is reusability. We can call afunctionasmanytimesasweneedto.Ifwecancallafunctionthatwe’vewritten,canwenotalsoallowotherstoreuseourcodetosavetheirtime?Andusethecodesofotherstosaveours?Well:yeswecan!Thiscontinuationof the ideaofabstraction isexplored indifferentwaysmuchmorefully in laterchaptersbut, it isworthunderstandinghere thatthepoweravailabletoyouthroughcodingdoesnotrequireyoutodoeverythingyourself.Youareableimmediatelytousethehigh-levelfunctionsthatothershavewritten,whichcanprovideyouwithextremelypowerfulcapabilities.Thesearecollectionsoffunctionsandobjectsthatgiveyoursoftwarecapabilitiescreatedbeforehandbysomeoneelse.

Questions1. Howwouldyoudescribewhatafunctionis,inthesimplestway?2. Whatareafunction’sparametersusedfor?3. Whatisafunction’sreturnvalueusedfor?4. Howcanfunctionsbeusedtobreakdownacomplexproblemintosmallermanageable

blocks?5. Writea functionwhichaccepts threeparametersasnumbers,and returns thevalueof

the sum of the three numbers. Call this function in your Python script and print theoutputtothescreen.

Page 46: Programming a Primer Coding Fo

TakingitFurther

Page 47: Programming a Primer Coding Fo

Chapter5

ClassesandObjects

You know what a model car or a model plane is. They are the small replicas we puttogether and painted as children.But the fact is thatmodels are ubiquitous. Banks usefinancial models to predict stock price movement. Weather forecasting is done byextrapolatingtheoutputofoceanandatmosphericmodels.Theenterpriseofscienceisanattempttodevelopsophisticatedmodelstodescribeandpredictthephysicalbehaviourofthenaturaluniverse.Engineersusemodelstocreateandtestdesignsforengines,computerchipsandrobots.

Inallofthesecases,whenIrefertomodelsIamreferringtoacomputermodeloracomputerprogram.Itissoftwarethatpredictstheweather,notahuman.Itissoftwarethatbuysandsells thousandsofshareseverymillisecond,notahuman. It issoftwarewhichguides a rocket out of the atmosphere and puts it on themoon, not a human.And thatmeansthatitisprogrammerswhodesignthesoftware-basedmodelsofphysicalrealitiesinordertosolvemanyoftheproblemsfacingsocietytoday.

Object-OrientedProgrammingPythonisanobject-orientedprogramming(OOP)languagewhichmeansthatitprovidesfeatureswhichsupportOOP.OOPisaprogrammingconceptusedinthecreationofmostmodernsoftware,designed tosimplify thedevelopmentofcomplexprogramsandmakecodemoremanageable,reliableandunderstandable.

Wehavenotcalleditsuch,butupuntilnow,wehavebeenwritingbasicproceduralprogramswhichhavetheirfocusonwritingproceduresoperatingonsomedata.InOOP,the focus shifts from procedures to objects. You can think of an object as a model,containingboththedataandfunctionalityrequiredtomodelarealworldobject,andtheyaredesignedtointeractwitheachotherinthesamewaythatrealworldobjectsdo.

In procedural programming we might write a function such ascountNumberOfSubstringOccurrences(some_string, some_test_ string) whichsuggests that the function is the active agent. We’re effectively saying to the Pythoninterpreter,“HeyPython,here’sarandomstring,canyoucounthowmanyoccurrencesofthissubstringthereareinit?”

InOOPhowever, it is objects that are considered the active agent.That is, it is theobjectwearecommandingtoperformsomeaction.Now,wemightdothefollowing:

Page 48: Programming a Primer Coding Fo

This short program uses the fact that a string in Python is an object, which has amethod (function) called ‘count’. This method accepts a string and returns a numberwhich, in this case, is the number of times the string occurs in the object string. Themethods of objects are accessed using the ‘dot notation’ exemplified above.The object(‘some_string’),usedintheexampleabove,isaPythonstringobject.Wethereforehaveaccess to all themethods that the Python string has, including the ‘count’method.Wespecifythenameoftheobjectfollowedbyadotfollowedbythemethodnametoexecutethemethodonthatobject.

Itmay not be immediately obviouswhy this change in perspective is useful, but itturns out that this shift from focusing on procedures to focusing on objects allows usgreaterversatilitywhenwritingprograms.Whenwethinkaboutit, thisconceptmatchesverycloselywithourexperiences in life.Whenwewant tocallsomeonewedonotuseourmicrowave,weuseaphone.Soaphonecanbemodelledashavinga‘call’method.But if we were modelling a microwave, it would not have that method, but a ‘cook’methodinstead.OOPallowsus tomirrorrealworldobjects inorder tomodel themandsolveproblemswhicharerelatedtothem.

Objectsdon’tevenneedtoexistinreality.Theycouldbehighlyabstractideasthatyoumayneedtocreate,suchasa‘Connection’object,ora‘DatabaseHandler’object.Theseareobjectswhichwouldhavevariables—knownasattributes—andmethods,butdon’tphysicallyexist.A‘Connection’objectcouldbeusedtomanageaconnectiontoaserverovertheInternet,andthe‘DatabaseHandler’maycontainmethodsforreadingandwritingdatatoadatabase.

InPython,everyvariableisanobject,whetheritisaninteger,adictionaryoraduck-billedplatypus.Programsmanipulateobjectsbyperformingcomputationswith them,oraskingthemtoperformmethods.Itishelpfultothinkofanobjecthavingbothastateandacollectionofmethods,thatitcanperform.Thestateoftheobject,representseverythingthatweknowaboutanobject,suchasaplatypus’ssize,colour,ageandcurrentdirectionoftravel.Aplatypus,forexample,hastheabilitytomoveindifferentdirections,toeat,tosleepandeventuallytodie.Theseactionscanbemodelledasmethodsandeachofthesemethodswillchangethestateoftheobject.Ifithasa‘moveForward’method,itsposition,directionandagewillbechangedbythetimethemethodhascompleted.

DefiningObjectsusingClassesYou may have already guessed that Python does not have a built-in ‘platypus’ object.We’vealreadyusedmanyofthebuilt-inPythonvariables,suchasstrings,integers,floatsand lists, yet in many cases we need to create objects which relate specifically to theproblemwe’retryingtosolve.

Aclass inPython, isa templateforanobject.Itspecifies theattributesandmethodsthateveryinstanceofthatclassshouldhave.Tothinkofitinadifferentway,anobjectisan instanceof a class— somethingwhichuses the template of a class but has its ownindividualstate.

When programming using an OOP language, we will typically create ‘classes’ tomodelarealworldobjectandthencreateobjectswhichareinstancesofthoserealworld

Page 49: Programming a Primer Coding Fo

objects. For example, I could create a class to describe a human that would have theinstance attributes ‘position’, ‘name’, ‘age’ and ‘gender’ among others, and could havemethods suchas ‘walkUpOneUnit’ and ‘changeName’. Iwould thencreate instancesofthisclasswhichrepresenteddifferentpeople.ForexampleIcouldcreateaninstanceoftheclass‘Human’whoseattribute‘name’wassetto‘Dave’,whoseheightwas190cmandsoforth.Fromheremanysuchobjectscouldbemade thatallhave thesamevariablesandmethods,butadifferentstate,sinceeachattributewouldbedifferentforeachobject.

Wecanmodela ‘Position’asanobjectwith twoattributes—andx-positionandy-position.Wecandefinea‘Position’objectbywritinganewclass:

Youwillbewonderingatthispointwhatthe‘__init__’functionisallabout.InPython,as inmostOOP languages, this is anexampleof a ‘constructor’. It is a function that iscalled automatically when an instance of a class is made. When, in this case, a new‘position’object ismade, its attributes need to be initialised to the requiredvalues.Forexampletocreatea‘Position’objectattheposition(3,7),wewouldcreateaninstanceofthis class and set x = 3 and y = 7. The ‘self’ keyword in the list of arguments for theconstructorrepresentstheobjectitself,andispresentintheargumentlistforeverymethodinaclass.Here’sournewPositionobject:myPosition=Position(3,7)

Inourexampleofaclass(above),we’vedefinedfourmethodsforthe‘Position’object— ‘getXPos’, ‘getYPos’, ‘setXPos’ and ‘setYPos’. Having created our object‘myPosition’,wecangetthex-andy-positionsoftheobjectbycallingthemethodontheobject.

Wecan,thensetthemtonewvaluesasfollows:

Page 50: Programming a Primer Coding Fo

Toclarify—wefirstdefinedaclasstomodelapositionandnamedit‘Position’.Wethencreatedapositionobjectcalled‘myPosition’,setitsinitialvalues,andprintedthemtochecktheywereset.Wethenusedtwomoreoftheobject’smethodstosetnewvaluesforthex-andy-coordinatesoftheobject,andprintedthemout.

Using the example from before, a ‘Human’ can be modelled as having a host ofattributesdescribingtheirstate,andoneof thesecouldbe,for instance, theirpositioninspace.Nowthatweunderstandwhataclassis,wecandefineanewclasswhichwillitselfcontaina‘Position’objectasanattribute.

Nowthatwehavedefined these twoclasses,wecancreatean instanceof ‘Human’,called‘Dave’.

Page 51: Programming a Primer Coding Fo

In defining the ‘Human’ class,we specified the attributes that each ‘Human’ objectshould have.We also defined amethodwhich prints the contents of that object to thescreen. You should be able to work your way through that method and see what ishappening.Try comparing the output of this program in the box abovewith the earlier‘printDetails’method,makingsureyouunderstandhowwegotthere.(Ifyoutryrunningthiscodeyourself,makesurethatboththe‘Position’and‘Human’classes,aswellasthecode above which creates the objects, are in the same file. Otherwise, if you just tryexecutingthethreelinesofcodeabove,thePythoninterpreterwon’tknowwheretofindourclassesandwillgiveanerror.)

Thefinal lineof theexamplecodeabovereadsprintdaves-Object.name.Wecanaccesstheattributesofanobjectusingthesamedotnotationasweuseforaccessingitsmethods. When attributes are initialised in the constructor of the class, they becomeavailabletobeaccessedfromoutsidetheobjectusingthisnotation.

InheritanceThere are a number of different relationships in the realworld between one object andanother,bothintheirbehaviourandintheirdesign.Bothintermsofdesignandbehaviour,apen isaverydifferentobject toapieceofpaper,however they interactwhen thepenwritesonthepaper.

Totakeaseparateexamplefromcricket,abatterinamatchisdifferenttoabowlerinhisorherbehaviour,butnot inhisorherdesign.Theway inwhich thebatter interactswithotherobjectsisverydifferenttothewayinwhichthebowlerdoesso,butashumanbeingstheyaredesignedverysimilarly.

InOOP,thisconceptiscalledinheritance.Thisisanobject-orientedconceptinwhichdesign and behaviour (attributes and methods) are inherited from other objects. Thisallowstwoclassestoinheritfromanotherparentclass,thussharingacommonderivativeintermsoftheirmostfundamentalattributesandmethods.

Totakeabasicexample:everyanimalhasaweightandaheight.Thereisnoanimalthatdoesnothavetheseattributes.Alionisananimalandsoinheritsalloftheseattributesfrombeingananimal,butalionhasamaneandatailinadditiontothesebasicattributes.

Ifweweretowriteclassesthatmodel‘lions’,‘goats’and‘camels’,wewouldneedtomake a comprehensive list of all of the attributes that are possessed by each of theseanimals.Manyofthesefeatureswouldberepeated,astheyarecommontomanyorallofthem.

Inheritanceallowsustodesignan‘animal’classandthenwritea‘lion’class,a‘sheep’classanda‘camel’class,eachofwhichbelongtothe‘animal’class.Thismeansthattheyautomaticallyhavealltheattributesgiventothe‘animal’class.Wecanthenaddfeaturesandbehaviourthatarespecifictoeachoftheindividualanimalclasses.

TakingtheexampleofabatterandabowlerinagameofCricket,we’regoingtousethe‘Human’classwecreatedearliertodesigna‘Batter’anda‘Bowler’class.Abowlerisahumanandinheritsthehumanattributes,butinadditionheorshehasabatterwhoalsoinheritsthehumanattributes.

Page 52: Programming a Primer Coding Fo

Boththebowlerandthebatterarehumans,buttheirinteractionwitheachotherisverydifferent.Thebowlerbowlstheballatthebatter,butthebatterstrikestheballwithhisbat.Theybothinheritmanycommonattributesfromthe‘Human’class,buttheirrole-specificbehaviourisaddedlaterasmethodswithintheirclasses.

Each of the two classes inherits from the ‘Human’ class, denoted by the ‘Human’object(thenotesinthebracketstotherightoftheclassnameintheaboveexample).Inaddition, a constructor (see above) is required to accommodate this inheritance byconstructing a human object with the correct initialisation (line three of each class).Classes that are inherited from a parent class, are called children or subclasses of theparentclass.

Themethods‘bowlAtBatter’and‘strike’areaddedtothe‘Bowler’and‘Batter’classesrespectivelysincetheyareadditionalmodelsofbehaviourthatarespecifictotheclassestheyarein.

Let’sexaminethedifferencebetweena‘Batter’anda‘Bowler’:

Page 53: Programming a Primer Coding Fo

Sincebotha‘Bowler’anda‘Batter’inheritattributesfrom‘Human’,theycanuseallthesameattributesandmethodsthat‘Dave’wasgivenpreviously.

Because‘isBowlerisanattributeaddedtoa‘Bowler’,wecangetitsvaluefromany‘Bowler’object,andsince‘isBatterisanattributeofa‘Batter’,wecangetitsvaluefortheobject‘batterJohn’.

Likewise themethod‘bowlAtBatter’ isavailable toa ‘Bowler’.Sincewepassed theobject‘batterAndy’intotheconstructorofthe‘Bowler’,wenowhaveaccesstoherorhisattributes and methods. Inside the ‘bowlAtBatter’ method of the ‘Bowler’ class, the‘strike’methodofthe‘Batter’isexecutedwhichmodelsabatterstrikingtheball.

You should have now grasped the basic ideas behind OOP including attributes,methods, constructors and inheritance. You’re not expected to be fully competent afterhavingreadthischapter,butmyintentionisthatyou’veunderstood—atleastinpart—someofthesedifficultconcepts.

Questions1. Howwouldyoudescribethedifferencebetweenaclassandanobject?2. WhatisOOP?3. Whatistheroleofamethodofaclass?4. Whatisinheritance?

Page 54: Programming a Primer Coding Fo

Chapter6

TheGraphicalUserInterface

Wehavebeenconsideringexamplesofcomputerprogramsthatareentirelycommand-linebased.Thatis,wehavebeeninputtingandoutputtingdatatoandfromthecommand-line.But when we hear about a new piece of software that’s been released, we are usuallyhearingaboutsuchthingsasanewsocialmediawebsite,aMicrosoftOfficeupgradeoranewappforoursmartphones,whichseemtobeverydifferenttowhatwe’vecoveredsofar.

Most software just appears towork likemagicwithwindowsappearingallover theplace,impressivegraphics,smoothtransitionanimations,internetconnectivityandmanymorefeatureswhichdonotseemlikesimplysetsofcomputerinstructions.

We must remember, however, that this is all that any program is — a set ofinstructions. There is no mystery behind real-time computer generated graphics or theWorldWideWeb (WWW).The programmerswho developedCall ofDuty andGoogleChrome did so by using programming languages that use the same principles aswe’vebeenconsideringinthisbook.Infact,manyofthefeaturesofourfavouritewebsitesusePython!Suchisthepowerof‘abstraction’.

Thecontrolandmanipulationofindividualpixelsonacomputerscreenisalow-levelcapability, but using software, we can build abstraction upon abstraction to generateclasseswhich,forinstance,canmodel3Dobjectsonourdisplaysinreal-time.And,usingabstraction,wecanwriteclasseswhichtakeabasicbinarysignalbetweentwocomputersandcreateapplicationswhichrunacrosstheInternet.

There isnomagic involved increatingfuturegroundbreakingapplications. Itcanbedonebyanyone.Aswegothroughthenextthreechapters,youwillbeamazedatjusthoweasyitistoimplementyourgeniusideas,nomatterwhattheyare.

wxPythonwxPython is a library for Python which abstracts away the complexities of generatingclasses fordrawingGraphicalUser Interfaces (GUIs)—thewindowswhichsurroundadesktopapplicationsuchasInternetExplorerorMicrosoftWord—ontothescreenofacomputer.wxPythonmakescreatingthesewindows,includingtheirmenus,tabs,buttons,sliders,grids,combo-boxesandmore,trivial.Itis,moreover,cross-platform,whichmeansthatitrunsonWindows,MacandLinuxcomputers.

We’regoingtostartwithaverysimpleexamplewhichdisplaysabasicwindowtothescreen.

Page 55: Programming a Primer Coding Fo

Muchofthiswill lookentirelyunfamiliartoyousoletusgothroughit linebyline.ThefirstlineisthepathtothePythoninterpreterthatwehavetoincludeatthebeginningof every programwewrite ifwewant to execute it without parsing it into the Pythoninterpretermanually(mentionedinChapter2).Thekeyword‘import’inlinetwotellsthePython interpreter thatwewant touse thewxPython toolkit, andso the interpreter thenfindsalloftheclassesthatwemayneedtouse.Then,inlinethree,wecreateawxPython‘App’objectwhich isanabstractobject to storean instanceofawxPythonapplication.Next,wecreatea‘Frame’object,whichisaninstantiationoftheclasswhichcreatestheoutermost window of our application. The three parameters to its constructor are theframe’sparent,whichdoesn’texist;anidentifierwhichwe’vesetto−1andthetitleoftheframe.Thisframeisaparentofotherwidgets(acomponentofanapplication)butdoesnothaveaparentitself.

We’ve then, in line five, executed the ‘Show’ method, to actually show our frameobject on the screen. Line six enters the applications main loop, which then endlesslycatchesanddispatcheseventsthatexistduringthelifespanofourapplication.

Despitethisbeingaverysimpleexamplewecandoalotwiththiswindow.Wecan,forinstance,moveit,re-sizeit,minimizeitorcloseitentirely.Allthisfunctionalitywouldnormallyrequireahugeamountofcoding,butthisisalreadyprovidedbywxPython.

Every individual item that can be placed inside awx.Frame is known as a widget.Thesearechildren to the ‘top-level’widget,which isusuallyawx.Frame. (Wecanalsouseothertop-levelwidgetsincludingwx.Dialogorwx.ScrolledWindow.)

Insideourtop-levelwidget,wecanplacethefollowing:

Containers,including

Page 56: Programming a Primer Coding Fo

wx.ScrolledWindowwx.Panelwx.SplitterWindowwx.Notebook

Dynamicwidgets,includingwx.ToggleButtonwx.CheckBoxwx.Buttonwx.RadioButtonwx.ComboBoxetc.

Staticwidgets,includingwx.StaticBoxwx.StaticTextwx.Gauge

Otherwidgets,includingwx.Toolbarwx.MenuBarwx.StatusBar

‘Containers’arewidgetsusedaschildrenof the top-levelwidget,and they ‘contain’otherwidgetsandarrangethemintherequiredformat.‘Dynamic’widgetsareinteractiveand can be clicked, checked, toggled or selected, depending onwhat they are. ‘Static’widgetsholdcontentandstayinoneplace.

Thethreeotherwidgetsarethemostimportantanddon’tfitintotheothercategories.wx.Toolbarandwx.MenuBarcontainordered‘buttons’thatcanbeprogrammedtoexecutespecificfunctionswhenclicked.Thewx.StatusBarwidgetittypicallyfoundatthebottomofawindowanddisplaysinformationtotheusertohelpthemunderstandwhatisgoingoninsidethewindowatanygiventime.

Iamnottellingyouaboutthesewidgetsontheassumpitionthatyou’llbeabletousethemstraightaway,but togiveyouan ideaofwhat’sout there foryou touse tocreateyourGUIs.Wewouldnotcoverthemall,butwe’lltryoutafewandhopefullythatwillgiveyoutheconfidencetouseotherresourcestofindthespecificwidgetsthatyou’llneedinthefuture.

TheMenuBarandButtonsAmenu bar in wxPython is an object which can be created by calling wx.MenuBar()whichistheconstructorforthe‘MenuBar’objectinthe‘wx’package.BelowwehaveacompletewxPythonapplicationdemonstratingarangeoffeaturesinwxPython,includingthemenubar,aniteminthemenubar,abuttonandadialoguewindow.

Page 57: Programming a Primer Coding Fo

Iwillgiveyouastep-by-stepoverviewofwhatwe’redoinghereasillustratedbythecodebelow.We’llgothroughitintheorderinwhichitgetsexecuted,sowecanseetheprocesstakingplace.

Page 58: Programming a Primer Coding Fo

Thefirstthingtonoticeisthatthelasttwolinesinthecodeare:

Youcanthinkof thisassimplycausingthefunction‘main’ tobeexecutedwhenthePython interpreter runs your program.What’s really happening ‘under the hood’ is thatPythonissettingitsspecialinternalvariable‘_name_’tothestring‘_main_’,inordertoexecutethemainpartofthePythonscriptit’sbeengiven.

Insidethe‘main’functionwhichPythonexecutesnext,ourexamplewxPython‘App’objectisinstantiatedandcalled‘ex’:

Page 59: Programming a Primer Coding Fo

Nexttheclass‘MyMenu’isinstantiatedandthenentersits‘MainLoop’whichcausesit to begin its normal operating cycle. Obviously, it’s inside ‘MyMenu’ that all theinterestingstuffhappens,solet’sopenupitsconstructor.

Ourmenubar inheritsfromthe‘Frame’object,soweneedtoruntheconstructorofthat object inside our own ‘__init__’ function. The keyword ‘super’ in the above codedenotestheclassfromwhichwe’reinheriting.Thefirstlineinitializesthis‘Frame’objectandlinksittoour‘MyMenu’class.

Nextweinstantiatea‘MenuBar’objectfromthe‘wx’libraryandnameit‘menubar’,and similarly instantiate a ‘Menu’ object called fileMenu. This is a childwidget to themenubar.Anewitemisaddedtothisfilemenuusingthe‘Append’method.Thismethodacceptsthreeparameters:anidentificationnumbertolaterassignanactiontoit;astringoftexttodisplayonthebutton;andadescription.The‘Append’methodaddsthefilemenutothemenubarthatwe’venamed‘menubar’.Next,wecallonthe‘SetMenuBar’methodwhichbelongstothe‘wx.Frame’classthatwe’veinheritedfrom,anditsetsupthemenubarinourframe.

We then create a ‘wx.Panel’ object which will be a container for our button. Weinstantiatea‘wx.Button’object,placeitinside‘panel’,assignitanidentificationnumber,anameandapositioninsidethecontainer,asrequiredbytheparametersofthebutton’sconstructor.

Page 60: Programming a Primer Coding Fo

The last two lines of the code in the box above set up what are known as ‘eventlisteners’. These can be thought of as objects that execute a function when an eventoccurs,suchasthepressingofabuttonorthemovingofamouse.‘wx.EVT_MENU’ishereusedtosetupamenueventlistenerwhere,inthiscase,wespecifythewidgetwithIDequal to 1 to execute the ‘OnQuit’ method that we’re to define. We also use‘wx.EVT_BUTTON’tocauseourbuttonwithIDequalto2toexecuteacommandcalledby us ‘OnButtonPress’. Both of thesemethods are specified in ourMyMenu class andwe’lltakealookattheminamoment.

Finally,wesetthex-andy-coordinates;thetitleandthepositionofourframe;andsetitsvisibilitystatetobe‘visible’.Allofthesemethodsareinheritedfromthe‘wx.Frame’object.

As shown in theexamplecodebelow, the ‘OnQuit’methodsimplycalls the ‘Close’methodinheritedfromthe‘Frame’classwhichcausesour‘MyMenu’objecttoclose,thatis:

When our button is pressed, the ‘OnButtonPress’ method is executed as instructed.Then,thefollowingthreelinesofcodeareexecuted:

Abuilt-in‘MessageDialog’objectiscreatedwhichdisplaysamessage.Itsparametersare the calling classwhich is ‘self’, the instruction text ‘PressOK’ and themessage todisplay—“Thisisamessagedialogue”.Thesedialoguesandothersareusefulforsuchtasksasnotifyingtheuserofsomething,requiringaconfirmationfromtheuser,acquiringatext-entryfromtheuserandarangeofothertasks.

The‘ShowModal’methodshowsthedialoguetotheuser.Theword‘modal’indicatesthattheusercannotdoanythingwiththeapplicationuntiltheyclick‘OK’onthedialogue.Whentheuserdoesclick‘OK’,thismethodreturnsandthedialogueisdestroyed.

This brief introduction to wxPython should have served to highlight the ease withwhich graphical programs can be designed using Python, as well as giving you themotivationandconfidencetodiscovermoreusesofwxPythonandtherangeofwidgetsitprovides.

Questions

Page 61: Programming a Primer Coding Fo

1. WhatiswxPython,andwhatisitusedfor?2. WhatisawxPythonwidget,andwhatdifferentwidgetsareavailable?3. Whatmethod of thewx.Frame class is called to select the size of theWindow to be

displayed?4. Whatisan‘event’inwxPythonandhowaretheyused?Howwouldyouspecifythata

certainfunctionshouldbeexecutedwhenabuttonispressed,usinganevent?

Page 62: Programming a Primer Coding Fo

WebDevelopment

Page 63: Programming a Primer Coding Fo

Chapter7

Sockets,NetworksandtheWorldWideWeb

The Internet in the 21st century— socialmedia, e-commerce, news and entertainment.Evenourpersonalbankingisnowonline.Butthishasnotalwaysbeenthecase.Thefirstcomputersonlyworkedononetaskatatime—ahighlyinefficientmethodwhichlackedthecapabilitythatuserssought.Theywerelargeandneededstoringinlargecooledroomswhichwerefarremovedfromwhoeverwasusingthem.

In the late 1950s, a big change occurred in computing. A remote connection wasestablished between computers which led to the idea that computers could be shared,allowingtheprocessingpowerofonecomputertobesharedbetweenmultipleusers.

In 1957 during theColdWar, the first unmanned satellite, Sputnik 1,was sent intoorbit by the SovietUnion. The fear of a ‘missile gap’ emerged, and in order to secureAmerica’s lead in technology, the United States of America founded DARPA — theDefence Advanced Research Project Agency— in February 1958. DARPA planned alarge scale computer network, in order to speed the transfer of knowledge andinformation. This networkwould later become theARPANET. This, and the scientific,military and commercial advances of several other concepts from the US, France, andEngland,amongothers,formedthemajorfoundationsofourmodernInternet.

NetworksTheInternetisaglobalnetworkofcomputersandotherdeviceswhichcommunicatewitheachotherandsharedata,butwhatexactlyisanetwork?Well,acomputernetworkisacollectionoftwoormorecomputerslinkedbyasharedconnection.Thismeansthattheycaninteractwitheachother,viathisconnection.Theycansharedatawitheachother,aswellasresourcessuchasprinters,modemsanddatastoragedrives.

When networks atmultiple locations are further connected to each other using, forinstance,sharedchannelsprovidedbyphonecompanies,computerscansendemails,sharefilesandprovidearangeofservicestoremoteusers.

Every network includes at a minimum at least two computers, as well as networkinterfacecards(NICs),aconnectionmedium(usuallyawire)andanetworkingoperatingsystem(OS),suchasWindows,OSXorLinux.

Examplesofthesenetworksinclude:

LocalAreaNetworksLocal area networks (LANs) are networks that are typically confined to a particulargeographicalarea,suchasauniversity,companyorotherorganization.Theycanlinkasfewastwocomputerstogether,butaretypicallycomprisedofmanycomputers,usedby

Page 64: Programming a Primer Coding Fo

many people. Standardised ‘networking protocols’ (rules governing the format ofmessagessentbetweennetworkedcomputers)haveledtothewidespreaduseofLANsinbusiness and educational organisations across the globe. In addition, wirelesscommunicationcanbeused,allowingdeviceswithwirelesscapabilitytoconnecteasilytoanetwork.ThesearecalledWirelessLANs(WLANs).

WideAreaNetworks(WANs)‘Wideareanetworking’connectsmultipleLANsthataregeographicallyseparated.ThisisaccomplishedbyconnectingthedifferentLANsbyphonelines,satellitelinks,and/ordatapacketcarrierservices(broadband).Wideareanetworkingcanbeassimpleasonemodemandacomputerforremoteuserstoconnectto,orascomplexasanetworkofhundredsofanorganisation’sbranchesconnectingfromallovertheworld.

TheInternetThe Internet is a worldwide network of connected smaller networks, providing datacommunication services to those who request it. The World Wide Web (WWW) isconsideredsynonymouswiththeInternet,andprovidesanetworkofglobalservicessuchasremotelogin,filetransfer,emailandwebsites,whichareaccessiblefromanycomputerconnectedtotheInternet.

With the massive increase in demand for connectivity, the Internet has become adigital highway for billions of users. Internetwebsites nowprovide social, educational,politicalandfinancialresourcestoeverycountryontheplanet.

IntranetSimilar to the Internet, an Intranet is a private network within an organisation whichprovidessimilarfeaturesastheInternet,butwhoseavailabilityislimitedtobeonlywithinthat organisation. Intranets are most commonly used for providing easy access tocorporateinformationwithinanorganisation.

Wheteverthetypeofnetwork,theyallusetwotypesofcomputers.Theseareclientsand servers. Physically these computers look similar, but their configuration and usagedeterminestheroletheyhavetoplayinanetwork.Aserverisacomputerconfiguredtoprovidesomekindofservice tootherserversorclientswithin thenetwork,suchas filestorage,printingservicesorothersharedresources.Aclientisacomputerinthenetworkwhichconnectswiththoseservers,orwithotherclients,toaccesssharedresources.

Aclient/servernetworkisthemostefficientwaytoprovide

Databases,Management of applications such as spreadsheets, accounting, communications anddocumentmanagers,Networkmanagement,Sharedfilestorage.

Page 65: Programming a Primer Coding Fo

At the heart of this kind of network is the concept of splitting the function ofapplications between the server and client to let the most appropriate functions becompletedbytherightcomputer,tobesharedwithotherusersinthedesiredmanner.

NetworkinginPythonAshasalreadybeenalluded to, inorder foracomputer tobeconnected toanetwork itmustbe runninganOS thatcanhandleconnections fromotherdevicesoveranetwork.Thankfully,mostmodernOSsupportthisfunctionalityandPythonenablestheunderlyingcapability of theseOSs to let programmers connect clients and servers together over anetwork.

Pythonprovidestwolevelsofaccesstonetworkedservices.Themostbasiclow-levelnetworking capability is provided by sockets. These can be thought of as connectionsbetween computers that allow clients and servers to access a network. They are theendpointsofabidirectionalcommunicationschannelbetweentwocomputers.

Pythonalsocontainslibrarieswhichprovidehigherlevelaccesstospecificprotocolsoperatingover the Internet, including thehypertext transferprotocol (HTTP)whichwillbe discussed later. The library contains classes for handling the communication of databetweenthetwoendpoints.

IPaddressesandPortsAn Internet Protocol (IP) address is a numerical address assigned to every device in anetwork, inorder to identify it.There isahugeamount toknowaboutIPaddressesandhow they identify a device and then establish a connection to it, but here we’re onlyconcernedwiththebasics.

TherearetwoprimarytypesofIPaddress—IPv4andIPv6(versions4and6).IPv4istheoriginalIPaddressformatwhichisstillmostcommon.Itismadeupofa32-bitor4-bytenumber,separatedinto4parts.

Abitisasingle1or0thatacomputercanunderstand.Abyteisagroupof8bits,eachofwhichcanbesettoadifferentvalue.Thebyte,althoughabinarynumber,hasadecimalrepresentation,asdepicted in the imageabove.Eachof the4bytesordecimalnumberswhichcompriseanIPv4addresscanrangeintheirdecimalrepresentationfrom0to255,andmakeuptheuniqueidentifierofthenetworkeddevice.

IPv6isthenewformatforIPaddresses.Itisalongeraddress,introducedasaresultof

Page 66: Programming a Primer Coding Fo

the rapidexhaustionof thepossiblevaluesofandIPv4addresswhichwouldeventuallylimitthenumberofdevicesabletoconnecttotheInternet.

TheillustrationaboveshowsanexampleofanIPv6addresswhichismadeupofafargreaternumberofbitsand,asaconsequence,hasamuchlargerrangeofpossiblevalues.This allows for a larger number of devices to be connected to a network, as there is agreaterrangeofuniqueidentifiersavailable.

In addition to IP addresses, the other important part of a connection between twocomputers is the port. A computer can be connected to multiple servers at once andtransmitdatatosomeorallofthemsimultaneously!Itcan,forinstance,beprintingafileusingoneserveronaLANatthesametimeasreceivingawebpagefromaserverontheInternet.Clearlythisrequirestwoseparateconnections—onebetweentheclientandtheprinting server, and one between the client and the web server on the Internet. As theclient only has one single unique IP address, another way is needed to provide adistinction between the two connections and prevent them from interfering with eachother.Thisiswhereportscomein.

Thinkofaport.Yes,arealworldport.Asinaportthatshipscomeinto.Theseportsare inasingle location, likeSouthampton,NewYorkorSydney,and theseportshaveasingle address that every shipheads towhen it needs todelivergoods.But thisdoesn’tmeanthatonlyoneshipatatimecanusetheport—rathertherearemultipleberthsatthesameportthatdifferentshipscanusetounloadtheircargo.

A port on a computer, is a bit like a berth at a real port and allows for multiplesimultaneousconnectionstodifferentdevices.

Port numbers are numbered for consistency and ease of use for programmers.Typicallyports0to1023arededicatedforusebytheInternet,butinpracticealmostanyportcanbeusedforanyservice.

Allofthismeansthatwhenmakingaconnectionfromonecomputertoanother,we’llneedtospecifybothanIPaddresstoconnecttoandaportnumber.

TCPandUDPWhenanychannelofcommunicationisestablished,boththesenderandtherecipientmustagreeonaprotocoltousebeforebeginningcommunication.Thinkofsendingorreceivingaletter.Awrittenorspokenlanguageisbeingused,andeachwordwesayisreceivedandinterpreted by the recipient. To ensure the letter is delivered, we need to specify theiraddressontheenvelopesothatthepostalserviceknowswheretodeliverit.Wealsowriteourownaddressontheback,sothattherecipientcanrespondtoourletterifrequired.

Page 67: Programming a Primer Coding Fo

Whenacomputertransmitsdata,itissentastinypacketsofinformation,likesendingaletter.Aswellastheinformation,thesepacketscontainasetof‘meta-data’or‘headers’which includes the IP address of the destination computer. These headers instruct thenetworkwhereandhowtodeliverthepacket.

There are two primary protocols used by computers to transmit data between them.These protocols are ‘TCP’ and ‘UDP’, with TCP standing for Transmission ControlProtocolandUDPstandingforUserDatagramProtocol.Theyeachuseslightlydifferentmeansofdeliveringpacketstoeachotherandeachhasitsbenefitsanddrawbacks.

TCPisamorereliable,connection-basedprotocolfortransmittingdata.Itrequirestwoavailableanchoredend-points,definingtheconnectionbetweenthesendinglocationandthereceivinglocation.UsingTCP,dataalwaysarrivesintheorderthatitwassent,andisonlyeverlostiftheconnectionisbroken.ATCPconnectioncanbebrokenifeitherend-pointlosesconnectiontotheInternet.

UDPisaconnectionlessprotocol.Thismeansthatdataissentregardlessofwhetherornot the computer at the destination IP address is available, existent or listening.Unfortunately, using UDP there is no guarantee that the data will ever be received.However when UDPworks it is a much faster method of transmitting data. The UDPprotocol,therefore,isparticularlygoodfortransmittingpacketscontainingpartsofmediafiles, such as steaming videos, where it doesn’t necessarily matter whether or not aparticularpacketisreceivedornot.

SimpleClient/ServerExampleAsocketiscapableofestablishingaconnectionnotonlyacrosstheworld,butalsofromonecomputerbacktoitself.Inorderthatwedonotneedtosetuptwocomputerstotalktoeachother,we are going to design twoprogramswhich talk to eachother on the samecomputer.Theprinciplefortalkingbetweentwoormoreseparatecomputersisexactlythesame,exceptwewouldneedtoknowtheseparateIPaddressesofthecomputersinvolved.

Firstoff,wehavegotaprogramtoactasaserver.Thisprogramwillcreateasocketandstartlisteningonport8089foraclienttoconnecttoit.Whenaclientisconnected,itwillsendamessagetotheclientandestablishtheconnection.

Page 68: Programming a Primer Coding Fo

In the two lines of the example program of the server above, we first import thePythonsocketlibraryandcreateasocketobjectbycallingtheconstructorofthe‘socket’classwithin thesocket’s library.We then find thenameof the localmachine (host)andbind the socket to this port using the ‘bind’method of the socket, whichwe’ve called‘mySocket’.ThehostinthisexamplecanbeconsideredsynonymouswiththeIPaddress.Thesocket’s‘listen’method—whichlistensonourportforconnectionsandreturnswhenaconnection ismade—is thencalled.We’veset thenumberofmaximumconnectionsthatcanbemadetofivebyspecifyingthisintheparameterforthe‘listen’methodofoursocket,‘mySocket.listen(5)’.

Lastly,our serverentersan infinite loop,whichneverendsbecause theconditionofthe‘while’loopisalwaystrue.Inareal-worldimplementationofaserver-sideprogram,this would be replaced with the specific functionality offered by the server.When theconnectionisestablishedbyacceptingtheconnectionrequest,boththe‘connection’objectandtheaddressoftheclientarestored.Bothoftheseobjectsarethenreturnedwhenthe‘accept’methodofthesocketiscalled.AmessageissentusingaTCPpackettotheclientusingthe‘send’methodoftheconnectionandfinallytheconnectionisclosedbeforetheloopisrepeated.

Theexample clientprogrambelow is simpler andmustbe executedafter the serverprogram as, if the client program is executed first, the port on the server will not belisteningfortheconnectionandwewillnotbeabletoestablishone.

Page 69: Programming a Primer Coding Fo

The client program similarly instantiates a ‘socket’ object. Since the client isconnecting to the same host as the server, namely itself, it can use the ‘gethostname’method,which also returns the IP addressof the localmachine.Everynetwork-enableddevicehasa ‘host’commonly referred toas the localhost.Weconnect to thesameportthattheserverisboundto,andthereforelisteningon,andattempttomakeaconnectionusing the ‘connect’ method on the socket. The ‘recv’ method of our socket recogniseswhenamessage is received from the server, and the returnvalue is thenprintedon thescreen,afterwhichtheconnectionisclosed.

Wefirstrunourserverinthebackground,byappendingtheusualcommandwithanampersand(&).Wethenrunourclientprogramandobserveouroutput.

Wecaninferfromthisoutputthattheserveriscorrectlysetupandboundtoport8089onthelocalhost.Wecanalsoinferthattheclientconnectedcorrectlytothesameport,andreceivedappropriatemessagesentfromtheserver.

This basic idea forms the basis of all networked applications, by providing aconnection between computers throughwhich information can be shared.A socket is avery primitive and low-level layer of abstraction connecting peers on a network, yet itforms the foundationuponwhichhigher-levelnetworkedapplications interactwitheachother.

Questions1. WhatdotheacronymsLANandWLANstandfor,andwhatisthedifferencebetween

them?

Page 70: Programming a Primer Coding Fo

2. WhatareIPaddressesandports?3. What is the difference between TCP and UDP as protocols for sending information

acrosstheInternet?4. Whatisasocket?

Page 71: Programming a Primer Coding Fo

Chapter8

HTML,CSSandJavaScript

Justbyglancingatthetitleofthischapter,youmaywellhaveseenabunchofnamesoracronymsyouknownothingabout,soI’mgoingtotellyouaboutanotherone,justtogetyou well and truly confuzzled. HTTP stands for HyperText Transfer Protocol, whichmeans that it is a protocol for transferringHyperText.HyperText is, in essence, regulartext with ‘links’ in it, where a ‘link’ is a shortcut to another web page. HTTP is theprotocolyouuseevery timeyou loadawebpageon the Internet. It is specifiedby thelittle ‘http://’ which comes before the ‘www’ in a website’s address, which tells yourbrowserthatyouareusingtheHTTPprotocoltoaccessthewebpage.

WecanuseHTTP toget information from just about anywhereon the Internet, andthisinformationcomesfromservers.TheInternetisfullofclientslikeyouandme,whoask for various resources. These resources include files, web pages, videos, pictures,applicationsandotherformsofdata,andtheyareallstoredonvariousservers.Whenyoumakea‘HTTPrequest’,youareburningthroughthenetworkuntilaserverisfoundthatisabletorespondtotherequest.Whenitfindsthatserver,theserverrespondstoyouwitha‘HTTP response’. A HTTP request is called a ‘GET’ request and a HTTP response iscalleda‘POST’request.AGETrequestseeksaresourcefromaserverusingHTTP,andaPOSTrequestseekstodeliverthatresourceusingHTTP.

HTMLMostdesktopapplicationsreadandwritefilesinaparticularformat.MicrosoftExcelcanhandle.xlsxor.xlsfiles.PowerPointcanhandle.pptxor.pptfiles.Thesefilesarenothingspecial,butaremerelyasetofinstructionsonhowtorebuildtheobjectscontainedinthefiles the next time they are opened in a compatible program. It is exactly the same forinternetapplications.

HTMLstandsforHyperTextMarkupLanguageandisusedtodescribethecontentsofawebpage, andhow it shouldbedisplayed. It is a languagewhich is understoodby abrowser and allows content to be sent as text over a network such as the Internet anddisplayed as required. It’s just a textual representation of content and how that contentshouldbeshownbythebrowserreceivingit.

ThestructureofaHTMLpageisfairlyconsistent,soitwillbebeneficialforyoutobecomefamiliarwiththeexamplebelow,whichisthecodedescribingaverybasicpage.

Page 72: Programming a Primer Coding Fo

The first thing you’ll notice is that there are lots of angle brackets (< and >)throughout,withkeywordsinthemiddle.The“<some_text>”partiscalleda‘tag’,andisusedtodenotethestartofaparticularsectionofcontent.Thisopeningtagisaccompaniedbyacomplementary“</some_text>”whichclosesthesectionofcontent.

Thereisalineintheaboveexamplewhichusesthe<title>tagshownbelow.Thisisatagwhichtellsthebrowserthatthetextinthemiddleofthe<title>tagisthetitleofthewebpage.Inourcase,wewantthetitleofthepagetobethestring‘Titleofpage’.Thecontentsoftagsareoftenreferredtoaselements.<title>Titleofpage</title>

You’llhaveseenfromoutpageoutlinethatatagcancontainothertagswithinit.Forexample the<html> tag is a tagwhich denotes the start and end of the contents of theHTMLpage.InsidetheHTMLelementarecontainedapairof<head>tagsand<body>tags which appear consecutively. The <head> element of a HTML page contains the<title>elementandcancontainarangeofadditionalmeta-datarelatedtothebehaviourofthepage.

The<body>elementcontainstheprimarycontentofthepageincludingheaders,sub-headers, paragraphs, images, links and much more. In our example we’ve included aheader (‘<h1><h1>’) followed by a paragraph (‘<p></p>’) and a sub-heading (‘<h2><h2>’)followedbyanotherparagraph.

YoucanviewaHTMLdocumentbysavingtheHTMLtoatextfilewiththe.htmlfiletypeanddraggingthefileintoyourbrowser.

As you can see from the screenshot above, this basic page is extremely plain andcontains no interesting colours, fonts, or stylingwhatsoever. This is something thatwesolveusingwhatiscalled‘CascadingStyleSheets’orCSS.

Page 73: Programming a Primer Coding Fo

CSSCascadingStyleSheets(CSSs)isalanguageforspecifyinghowHTMLpagesshouldbedisplayed to users. Take the example below — a modified version of our previousexample. Here, we’ve placed a paragraph element within our main body, and haveencapsulatedthefirstletterofeachwordinsideapairof<strong>tags.A<strong>tagisatagbuiltintoHTMLwhichgivesastrongerfonttothenextelementcontainedwithinthetag.

You should observe the following output, where the first letter of eachword has aheavierfontthantherestoftheword,aswespecified.

(Duetoyourspecificbrowser,thismaynotnecessarilyappearexactlythesameasthescreenshotabove,butthedifferencesarenotimportant.)

AtpresentwearenotusinganyCSSatall,butwecanincludeCSStodefineastyle

Page 74: Programming a Primer Coding Fo

forourwebpage,includingthedesign,layoutandvariationsfordifferentdisplaysizes.

Hereisourfirstcascadingstylesheet,savedasafilecalledstyle.css:strong{color:red;}

This says that for <strong> tags, the colour is set to red. This same syntax can beappliedtodifferenttagsandcanbeusedtosetarangeofdisplayoptions.Now,wemodifyourHTMLtolinkittotheCSSfile.

Asyoumayhaveguessed,thiscausesthelettersenclosedinthe<strong>tagtobenotonlybolder,butalsored.

The ‘<link>’ element in the example above contains two attributes which provideadditionalinformationaboutHTMLelements.A<link>elementlinksaHTMLpagetoanexternal style sheet (ESS). The attribute ‘rel’ stands for ‘relationship’ and specifies therelationship between the current document and the linked document. ‘href’ stands forhyperlinkreferenceandcontainstherelativepathtotheCSSfiletobelinkedthecurrentdocument.

The following example uses the originalmodification of the <strong> element, butalsoaffectsparagraphtags(<p>).We’veaddedtwostylisticfeaturestotheparagraphs—we’vechangedthecolourtoblue,andindicatedthatthetext-decorationbeunderlined.

Page 75: Programming a Primer Coding Fo

Sincewe’venowgotamorecomplexstyle sheet,we’veproperly indentedourCSSfiletobemorereadable.

Youmayhavenoticedthatthetextinsidethe<strong>tagisalsoinsidethe<p>tagandthattherearedifferenttextcolourspecificationsforeach—inthe<p>tagthetextisblue,butinthe<strong>tagitisred.Inthiscase,sincethe<strong>tagisinsidethe<p>tag,itisthelasttagtoaffectthecontentsofthatelement,sothestyleforthe<strong>tagtakesprecedence.

ThefinalthingweneedtobeintroducedtoisthemostpowerfulandimportantHTMLelement.It’scalledthe‘<div>’tagwhichstandsforadivision.We’regoingtotakealookatitherebecauseit’sonlyrelevantwhenusingCSS.It’satagusedtoseparateonepieceof content from another. Completely controllable using CSS, <div> tags are highlyflexibleintermsoftheirposition,behaviour(as,forinstance,whenthepageresizes)andtheircontent.

Page 76: Programming a Primer Coding Fo

Thecode in thepreviouspage illustrates theuseof two<div> tags.Asyoucanseefromthescreenshotbelow, thedefaultbehaviourofa<div>tag is tocontain itscontent(textinthiscase)inaverticalorder,similartothe<p>(paragraph)element.

Theaboveexampleuses<div>tagswithnostyleformattingwhatsoever.Howevertheprimarypurposeof<div>tagsistheirabilitytobeusedtospecifythestylebehaviourofapartofawebpage.

TheexamplebelowisaHTMLpagecontainingaselectionof<div>tagswhichshowsthisclearly.We’vesurroundedourcontentina<div>tagwith‘id’attributesset,wherean‘id’ attribute is away to identify a particular tag, usingCSS to provide itwith custom

Page 77: Programming a Primer Coding Fo

styles.We’vesurroundedboththeheader,thecontentandthefooterofthisexamplepagewith<div>tagsandhaveusedappropriate‘id’valuesforeach

TheCSSfile‘style.css’isshownnextandisusedtocomplementthisHTMLpage.InCSS, the elements of a pagewith an ID set (denotedby the ‘id’ attribute) are accessedusing a # symbol followed by the value of the ID. Within the block inside the curly

Page 78: Programming a Primer Coding Fo

brackets, we can then specify the style to be applied to the elements that have beenaccessedusingthatID.

Thescreenshotbelowillustrateswhattheoutputofthispagelookslike.We’vesetthebackgroundcolouroftheelementwithID‘header’and‘footer’tobegreenandtheborderoftheelementwithID‘content’tobeonepixelwide,andtoalsobegreen.

AsyoucanseefromtheCSSabove,thetextalignmentofthetextwithinthecontenthasbeen set to ‘left’whereas the footer text alignment is centred.The ‘margin-bottom’styleattributegiventothe‘h1’tagdenotesthatablankmarginofsize10shouldbeaddedtothebottomofeveryheader.Thiscanbeseenastheblankspaceunderneaththeheaderinthepagescreenshotinthepreviouspage.

Ascanbeseen,<div>tagsareimmenselypowerfulforahostofreasonsandthevastmajority ofmodernweb pages are based on the interaction ofCSSwith <div> tags inHTML.

JavaScriptWehaveallusedsomeprettyfancywebapplicationsaswebtechnologyhasprogressed,whether Netflix to watch movies or Facebook with awesome features like chat and

Page 79: Programming a Primer Coding Fo

notification.Whilewe’vebeenintroducedtoHTMLandCSSalready(bothofwhichareusedbythesepopularwebapplications)youmaysuspectthatsomethingmoreisrequiredformuchofthebehaviourdemonstratedbythesesites.ThatsomethingisJavaScript.

OneofthebrilliantthingsaboutusingJavaScriptit thatisrequiresalmostnosettinguptobeabletodevelopandtestyourownJavaScriptcode.Allyouneedisatexteditor,and a web browser like Google Chrome or Mozilla Firefox. To try out the followingexamples,youcansimplycopythemintoyourown.htmlfile,andthentesttheminstantlysimplybydraggingthefileintoyourbrowser.

JavaScript is a language that is used to add behaviour to the ‘front-end’ of a webapplication.The term front-end, refers to theclient’s computer asopposed to the serverhosting thewebsite.Thus,JavaScript isan interpreted language that issent to theclientwhenapage is requested from thewebserver.When itarrivesat theclient, theclient’sbrowserexecutestheJavaScriptcodeandsomeoperationisperformed.

JavaScriptcodecanalsobeexecutedwhenauserinteractswithapage,suchasatthetouchofabuttonormousemove.Itcanbeused,for instance, tovalidateauser’s inputintoatextfield,toprovidedraganddropfunctionality,tochangethestyleofthewebpageon-the-fly,toanimatepartsofthepageandeventodeliverrichgraphicsthattheusercaninteractwith.

All this functionality revolves around the idea of event handling. This is a conceptthat’snotuniquetoJavaScript,butwhichisfundamentaltounderstandinghowitworks.AlmosteverypieceofJavaScriptistriggeredasaresultofanevent.Eventscanbepageloads,buttonclicks,mousemoves,doubleclicksormousedrags,andamultitudeofotherthings.

Thespecificsofeventhandlingarefartooextensivetobecoveredinthischapter,butwe’ll use the next few pages to go through a couple of examples to demonstrate somedifferentways to includeJavaScript inawebpageandaselectionof thingsyoucandowithit.

In thesamplecodebelow,allwe’vegot isaparagraphelement<p>.Theparagraphelement has an attribute ‘onclick’,which is anevent listenerwhich listens for a ‘click’event.Thevalueassignedtothe‘onclick’attributeisastringcontainingJavaScriptcode.<ponclick=“alert(‘HelloWorld!’);”>ClickHere</p>

This example can be inserted into our original basic HTML page in the <body>element, or can be used as a stand alone HTML document. When we open it in ourbrowserandclickthetextintheparagraph,analertdialogueappearsdisplayingthetext‘HelloWorld!’,asshownbelow.

Page 80: Programming a Primer Coding Fo

The JavaScript codeexecutes thebuilt-in JavaScript function ‘alert’whichproducesthisdialogue.Theparameterofthismethodisthestringoftexttodisplay.Alertdialoguescanbeused ina rangeof situationsonawebpage,but fornow,we’reonlyusing it toillustratehoweventswork.

Ofcoursetheabilitytoproduceabasicmessageboxisnothingexciting,sowhataboutifwewantedtodosomethingmoreinterestingwiththesameevent?Letuslookatamorecomplex example. Instead of calling JavaScript’s built-in dialogue function directly,wecancallourownfunction.

Inthisexample,we’veusedtheHTML<script>element.Withinthe<script>tags,wecandefineourveryownJavaScriptfunctionfromscratch,rightwithinourHTMLpage.When our paragraph is clicked, JavaScript will resolve the ‘onclick’ event handler toexecuteourownfunction‘clickHandler’thatwe’vedefinedalready.Thisproducesexactlythesameresultasbefore.

Itisprobablyworthnotingherethataswithmostprogramminglanguages,thesyntaxofJavaScriptvariessomewhatfromPython.InPythonweusedindentationtodenotethestart of a method. In JavaScript, a function (effectively a method) is denoted by curlybrackets‘{}’,ascanbeseenintheexampleabove.Insteadof‘def’asusedinPython,inJavaScriptthekeyword‘function’isusedtodenotethestartofafunction,andisalwaysfollowedby thenameof the function.Parameters are specified in thebrackets, and theindividualinstructionswithinthefunctionarespecifiedinthecurlybrackets.

WecanalsoincorporateJavaScriptfromanexternalfileusingtwoattributesinsidetheopening<script>tag.<scripttype=“text/javascript”src=“scriptName.js”></script>

The‘type’attributedenotesthatweareincludingtextcontainingJavaScriptcode,andthe‘src’(source)attributespecifiesthepathtothefilewhichcontainstheJavaScriptwewishtoinclude.

Page 81: Programming a Primer Coding Fo

We can perform complexmathematics in JavaScript, which can be explained usingsimple examples. In the example below, for instance, we’ve specified three elementswithinour<body>tag.Theseareablankparagraphelementwiththe‘id’attributesetto‘demo’; a <script> element with a function defined; and our original button with an‘onclick’eventlistener.

The ‘id’attribute isan identifier for thatelementwhichcanbeused inanumberofwaystoaffectthatelementaswellastheformatofitscontents.TheJavaScriptkeyword‘var’denotes thedeclarationofavariable. Inour function ‘myFunction’,we’vedefinedtwovariableswhichareassignedthenumbers2and3.Thethirdlineinsidethisfunctioniswheretheactionhappens.Inwords,weareresolvingthesumofxandyandassigningtheresulttotheinnerHTMLoftheelementwiththeID‘demo’.TheJavaScriptenginewithinyour browser is actually doing the following — taking the built-in JavaScript object‘document’whichisyourwebpage;usingits‘getElementById’methodwhichreturnstheobjectrepresentingtheelementwiththeIDpassedintothatmethod;gettingtheinstancevariable ‘innerHTML’ of that element which is the text inside the element’s tags; andsettingittothestringconversionofthenumericalsumofthevariablesxandy.Here’sthepagethatyouwillseeoncethe‘ClickHere’textispressed:

This ability of JavaScript is a hugely powerful feature, because it enables webdeveloperstochangethecontentsoftheirwebpagesaftertheyhavealreadybeenloaded.

Inadditiontocreatingdialoguesandperformingcalculations,JavaScriptisperfectforthegraphicalmanipulationofwebsites.Itisusedtomoveelementsaround,changetheir

Page 82: Programming a Primer Coding Fo

sizesandorientations,andevenreplaceoldcontentwithnewcontent.Inthefinalexamplepagebelow,we’vemodifiedour function toget theparagraphelement<p>with the ID‘demo’andchangethecolourofthetextinsideittogreen.

Whenthetext‘ClickHere’ispressed,‘myFunction’isexecutedandthe‘color’ofthe‘style’attributereferringtotheelementwithID‘demo’ischangedto‘green’whichsetsthefont’scolourtogreen.

The image above illustrates the contents of this page when the ‘onclick’ event ishandledbyourfunction.

ThiscombinationofHTML,CSSandJavaScriptformsthebasisofthevastmajorityoffront-endwebsites.Thereareawholehostofdifferentfunctionsthatwe’venotcoveredinthisbriefintroduction,howeverwhatwehavecoveredshouldhaveprovidedyouwithenoughunderstandingtogetthegeneralgistofhowwebpageswork,andgivenyoutheconfidence to investigateforyourselveswhatmorecanbedone tomake theuser-facingsideofyourwebsitesfull-featuredworksofart.

Questions1. Whatarethetwopiecesofinformationneededforaclienttoconnecttoaserverusinga

socket?2. WhatdoesHTMLstandforandwhatisitusedfor?3. Which language does a stylesheet use to manage how a HTML page appears on a

Page 83: Programming a Primer Coding Fo

device?4. What is CSS used for and how can it be used to change the colour of a paragraph

elementinHTML?5. HowisaJavaScriptfunctionexecutedfromwithinaHTMLwebpage?6. WhichJavaScriptfunctionisusedtodisplayapopupboxtotheuser?

Page 84: Programming a Primer Coding Fo

Chapter9

PHPandSQL

Whenyouwalkintoanup-marketrestaurantforyourfavouritecuisine,youwillnodoubtbegreetedbyyourwaiterorwaitresswithawelcomingsmileandguidedtoacomfortablechair in pleasant surroundings. That is because customer service in restaurants is ofupmost importance for retainingconsumersbygiving them the incentive tocomeback.Whiletheremaybeahostofchefsinthekitchenpreparingyourdinnerandgettingtheirhandsdirty,youarekeptblissfullyunawareofwhatbackgroundstresses,hardworkandskillsmayberequiredtomakeyourrelaxingeveninghappen.

Inthedevelopmentofwebapplicationsthesameprinciplesareapplied.Theimportantfunctions—oftenlargeandcomplex—areperformedforyouautomaticallyontheserverbeforethewebpagereachesyourbrowser.Allthecomputationalrequirementsaremetbytheserver,andaneat,tidyproductisthendeliveredtoyourcomputer.

Sofarwehavehadalookatsomeofthefront-enddesignprinciplesthatareusedtodevelop user-friendly, functional and beautiful interfaces for us to usewhenwe visit awebsite.However, forverycomplexwebsites,mostof thecode iswrittenfor theserverandisexecutedontheback-end.Thiscodeisnotconcernedwithhowattractivetheresultsare, since no user ever has to see them.Rather, this code is there to handle server-sidefunctionality, such as interacting with a database, storing files, processing user data,handling email, processing payments, collecting data from external websites, providinguserauthenticationandmuchmore.

For these tasks,weneedanew language.Languagesused server-side areknownas‘server-sidescriptinglanguages’andthemostpopularisPHP.Othersexist,suchasPerl,andRuby,aswellasPython,whichwearealreadywellacquaintedwith.

In addition to scripting language, server-side programs for websites typically use adatabase ‘querying language’. These are very highlevel languages used to create, read,updateanddeletedatafromdatabasesandtablesthatarestoredonaserver,andwe’llbeintroducedtooneabitlateron.

PHPAwebserver,aswehavealreadyseen,isaserverwhichrespondstoHTTPrequestsfromaclientwithinanetwork.Webserversoftwareisrequiredtobeinstalledonawebserver.ThisissoftwarewhichbindstoaHTTPportonyourserver,listensforHTTPrequestsandknowshowtoanswerthem.

PHPisthemostpopularscriptinglanguageonthewebanditisalanguagewhichsitsontopofyourwebserversoftware.WhenaclientrequestsapagethatcontainsPHPcode,yourwebserverexecutesitandsendstheresultantwebpage(withoutPHP)toyourclient

Page 85: Programming a Primer Coding Fo

usingaPOSTrequest.

LikePython,PHPisascriptinglanguage,whichmeansthatit’snotcompiledbeforeitisexecuted,butratherisprocessedandexecutedon-the-fly.Itisafairlycrypticlanguageintermsofitssyntaxsowewouldnotspendtoolonggettingconfusedaboutit,butwe’lllearnenoughtogiveusageneralideaofhowitcanbeusedto:

Takeinformationfromweb-basedforms,Authenticateandtrackusers,Handlecommendsandthreadeddiscussionsonawebsite,Servedifferentpagestopeopleondifferentdevices.

AsIhavesaidbefore,thisbookisnotintendedtobeaset-by-steptutorial,butifyouwanttoexecutethiscodeyourselfyouwillneedawebserverinstalledonyourcomputerandyou’ll alsoneed to installPHP. If you’reonaWindowsmachine,youcan install aWampServer (www.wampserver.com/en), or if you’re on a Mac you can use MAMP(www.mamp.info).Ifyougetstuck,thereareplentyoftutorialsouttheretohelpyougetaworkingwebserverandPHPenvironmentsetuponyourownmachine.

Oneof thewonderful thingsaboutPHPis that it letsyouembedyourcodewithinaHTMLpage,tobeexecutedwhenthepageisrequested.PHPcodeisenclosedwithinthetagsshowninthebasicexamplebelow.‘<?php’isusedtoopenablockofPHPcode,and‘?>’closesit.

Thisbasicexamplesimplyprintsthetext“Hello,world!”tothescreenwhenthepageisrequested.

Aswe sawwhenwewere learning Python, variables are the bread and butter of aprogram,astheyareusedtostoretheverydatathataprogramiswrittentoprocess.PHPsupportsanumberofdifferentvariable types, includingintegers(INTs),strings,floatingpointnumbers,andarrays,and,similartoPython,isabletoautomaticallyfigureoutthetypeofvariablebeingused.PHPvariablesmustalwaysbeprecededwithadollarsign($)and begin with either a letter or an underscore followed by any sequence of letters ornumbers.

Here’sanexampletoillustrateafewnewthings,includingPHPvariables.OurHTMLpage contains a<body> elementwhich holds both a paragraph elementwith an extractfromatranscriptofaplayandablockofPHPcode.

Page 86: Programming a Primer Coding Fo

First,withinthePHPcode,wemakeahelpfulcommenttoexplainwhatthenextfewlines do. This is done using the double backslash in PHP (‘//’). We then define thevariables ‘$name’, ‘$rank’ and ‘$serialNumber’. In this example, ‘$serialNumber’ isinitialisedwithanumber,whereasthefirsttwovariablesareinitialisedwithstrings.PHPunderstandsthisandautomaticallycreatestwostringvariablesandoneINTvariable.

Next,theexampleaboveusesthe‘echo’keywordtoprintsometexttothescreen.Inessence,the‘echo’keywordreplacesthePHPblockwhichenclosesitwiththestringthatthenfollows.Inourcase,thestringisenclosedwithinaparagraphelement,denotedbythe‘<p></p>’ tags at either end. Within these tags are included two bold elements ‘<b>’whichprintboldtexttothescreen,andanitalicselement‘<i>’whichprintstextinitalicstothescreen.Withintheseelementsarethevariablesthatwe’vepreviouslydefined.PHPautomaticallyconvertsthesevariablestothecorrectformatforprintingasastring,sotheinclusionof thesevariableswithinour stringenables thecontentsof thevariables tobedisplayedaspartofthetotalstringthat’sbeingprintedbythe‘echo’keyword.

As a brief exercise say out loud (or write on a piece of paper) the output of thisprogramandtrytovisualisewhatyouwouldsee.

Aswe’veseeninChapter9,therearetwowaysthatabrowsercansendinformationtoawebserver.

AGETrequestAPOSTrequest

BoththeGETandPOSTrequestsareusedtorequestdatafromthewebserver.Whenyouuseyourbrowser tonavigate towww.google.com, thisaddress forms thebasisofapagerequest.

Page 87: Programming a Primer Coding Fo

TheGETMethodYoumayhavenoticedthatsometimeswhenbrowsingtheInternet,theURLintheaddressbarofyourbrowsercontainsaseriesofkey/valuepairsaftera‘?’symbol.AnexampleistheURLbelowwhichformsthebasisofaGETrequesttoGoogle.https://www.google.com/search?q=facebook

As you can see, we’re using the HTTPS (encrypted HTTP) protocol to accessGoogle’s search page, but from here things may get unfamiliar. This base URL isappended with ‘?q=facebook’. Here the ‘?’ denotes the end of the page URL and thebeginningofalistofkey/valuepairs.Inourcase,thekey‘q’issetto‘facebook’.

PageswritteninPHPontheservermaycontainvariablesthatcanbeassignedbytheclientupontherequestingofthepage.WehavetakenabrieflookatPHPvariablesabove,but theyhaveallbeenassignedbyusinsidethePHPcodeof thepage.Thesekey/valuepairsallowus toset thevalueofsomeparameters in thePHPcodewhenweaccess thepagefromthewebserver.

Intheexampleabove,thereisavariable‘q’insidethePHPcodeoftheGooglesearchpage, which is open to be set by the user. We’ve set this variable equal to the string‘facebook’.Googlethentakesthisstringandusesitasthesearchphrasebeforereturningalistofsearchresults.

Try putting this URL into your browser and observing the results. You can evenchange the value of this parameter and watch Google return a different set of searchresults.

Whenauserrequestsapageusingtheirowninformation,aGETrequestencodesthisinformationintotheURLofthepagerequest.So,whenItype‘Facebook’intothesearchbox onGoogle’s homepage,my browser encodes this string into the URL of the pagerequestproducingarequestsimilartotheexampleabove.

Youmaywellbewonderinghowexactly thisall looks inPHP. IfmyPHPvariablescan be set by the user requesting the page, how exactly dowe choosewhat to dowiththosevariables?TheexamplebelowservestoillustrateexactlywhatitmeanstoproduceaGETrequestandhandleitinPHPontheserver.

ThisexampleisacompletePHPpage—itdisplaysaformtotheuser,allowsthemtoenterdata,thisissubmittedtotheserverandthensentbacktotheclientasHTML.

Page 88: Programming a Primer Coding Fo

Let’slookattheHTMLpartfirst.We’vedefineda‘<form>’elementwhichdisplaysdataentrywidgetswhichallowtheusertoenterdata.The‘action’attributeinthisexamplehasbeensettowhateverisresolvedbythePHPcode<?php$_PHP_SELF?>.ThevariableusedhereisaninternalPHPvariablewhichisalwaysequaltothenameofthepagethatit’scalledfrom.This‘action’attributethusdefinesthepagethatourformsubmitsto.Theuseofthisinternalvariablewillensurethattheformalwayssubmitstothispage,evenifitsnamechanges.We’vesetthe‘method’attributeto‘GET’whichdenotesthatwewishtouseaGETrequestasopposedtoaPOSTrequestwhensubmittingourform.

The<form>elementcontainstwo‘<input>’elements.Theseareinputboxesfortextinput (denoted by the value of the ‘type’ attribute). We’ve defined their names to be‘name’and‘age’whichdepict themeaningof thedata they’re tocontain.In theclosingtag of the form,we’ve specified the ‘type’ to be ‘submit’which automatically places a‘Submit’buttonatthebottomoftheformtoexecutetheGETrequest.

Turningourattentionto thePHPcodeabove,wenoticefirstofall thekeyword‘if’.This keyword performs the same logical operation for decision making as the Pythonequivalent.InPHP,an‘if’statementmustbeenclosedinbrackets.Thetwoparallelbars(||)arePHP’slogical‘OR’symbol,whichensurestheconditionresolvestobetrueifeither

Page 89: Programming a Primer Coding Fo

oftheconditionsoneachsideofitaretrue.

EachsideofthissymbolaretwovariableswhichaccesselementsintheinternalPHPdictionary‘$_GET’.ThisisavariablewhichisinitialisedwhenthepagereceivesaGETrequest.Everykey/valuepairintheURLofthepagerequestisaddedasakey/valuepairtothe‘$_GET’variablewhichthenallowsustoaccessthosevaluesfromwithinourPHPcode.Forexample,whenweusethephrase‘$_GET(“name”)’inPHP,we’relookingforthevalue in the$_GETdictionaryvariablewith thekey ‘name’.Sinceour formusedaGET request, this value should be the contents of the ‘name’ input field on theHTMLpagewhentheformwassubmitted.

In other words, what we’re saying in this example of PHP is “if the value of theelementinthe‘$_GET’dictionarywithkey‘name’isset(evaluatestotrue),orifthevalueoftheelementinthe‘$_GET’dictionarywithkey‘age’isset,executethechunkofcodebetweenthecurlybrackets”.

Withinthisblock,weprint‘Welcome’,followedbythevalueofthe‘name’parameterin theGET request, followedby a<br> element.We thenprint ‘You are’, followedbytheirsubmittedage,followedbythestring‘yearsold.’.

Trywritingouronapieceofpaperthefullstringthatwouldbeprintedifyouenteredyournameandage.

Threethingstonote:

The<br>elementisabreak,whichsimplyinsertsanewlineLinesofPHPcodewhichexecutesomething,mustendwithasemi-colon‘;’Exit()isabuilt-inPHPfunctionwhichstopstheexecutionofthescriptThedotoperator(.)isthesymbolthatPHPusestoconcatenatestrings

ThePOSTMethodUnliketheGETrequest,thePOSTrequestdoesnotsendtheuser’sdataintheURLofthepagerequest, instead itsends it to theheaderof theHTTPrequest.Thismeans thatanydatatheuserwantstosendtothePHPpageonthewebserverisstoredwithintheHTTPrequest.YoudonotneedtoworryaboutwhataHTTPrequestisexactlyatthisstage,butjustrememberthatdatasentusingaPOSTrequestisnotsentinthepagerequest.

DatasentusingaPOSTrequestisnotlimitedinitssize,asitisinaGETrequest,so

Page 90: Programming a Primer Coding Fo

when largefilesneed tobeuploadedfromaclient toawebserver throughawebsite,aPOSTrequestshouldbeused.

The example below is almost exactly the same to our previous example of a GETrequest,butthewordGETisreplacedwithPOST.

TheformsubmissioninHTMLandtheaccessingofthekey/valuepairsinthePOSTrequestareexactlythesameasbefore.Theonlydifferenceisinthewaythatthisdataissent.Asnoted,datasentinaPOSTrequestisnotintheURL,butintheHTTPrequest.This leads to amuch cleanerURL.POST requests are also typically better for sendingsensitive data such as passwords and personal information, since this data will not bevisibleintheURLofthepage.

PHP is a hugely powerful and flexible language for theweb. It is themost popularserver-side scripting language for websites and offers a range of features for almostanythingyou’llneedtodointermsofhandlingdata.

SQLDataistheprimaryassetthattheInternethandles.Arguablyisittheonlyassetthatitcanhandle.TheInternetisjam-packedwithdataandeveryonewithaPCandanetworkcablecanaccessit.Allofthisinformationneedstobestoredsomewhereandinaformatwhichmakesiteasyandfasttoaccess.

Structured Query Language (SQL) is a high-level languages designed for quicklycreating,reading,updatinganddeletinglargesetsofdata,storedinrelationaldatabases.Itis used by server-side applications, so a brief introduction to it at this point willcomplementourbasicunderstandingofPHP.

Theconcepttounderstandisthis—aqueryinSQLisdefinedandexecutedinPHP,usinganSQLdatabasewhicheithercreates, reads,updatesordeletesdatastoredin that

Page 91: Programming a Primer Coding Fo

database.IftheSQLqueryreadsdata,forinstance,thedataisreturnedwhentheSQLisexecutedinPHP,sothatdataheldinadatabasecanbeprocessedinPHPandlatersenttoauserovertheInternet.YoushouldbeawarethatSQLcanbeusedinarangeofdifferentprogramminglanguages,butsincewe’relearningPHPwewillseesomeexamplesofitsuseinthatcontext.

Inorder tobecomeacquaintedwithSQLusingPHP,we’ll firstget togripswith thesyntaxofSQL,andthenseehowwecanrunSQLqueriesinPHP.

Often ina ‘relationaldatabase’,data isbest stored incollectionsof tables.Hence,arelationaldatabasecontainsdatabaseobjectscalled‘tables’whichcontaindatarelatedtoeach other in some way. These tables contain columns and rows— items of data arestoredinrows,andarerelatedbysimilaritiesineachcolumn.

Databasesoftencontainmore thanone table.Forexample,acompanysellingsportsclothingonlinemightuseadatabasetostorealltheinformationrelatingtotheircustomersandtotheproductstheyhaveforsale.Theymayhaveatablecalled‘Customers’tostorealltheinformationtheyhaveabouttheircustomers,andatablecalled‘Products’tostorealltheinformationabouttheirproducts.

Thetable‘Products’mightlooklikethefollowing,whichcontainsfourcolumnsandfivedifferentrecords:

ThefollowingSQLqueryselectsalloftherecordsinthistablecalled‘Products’.SELECT*FROMProducts;

It’sworthnotingthatSQLstatementsarenotcasesensitive,sowecouldjustaseasilyusethestatementbelowtoachievethesame:select*fromProducts;

When this statement is executed the following data will be returned— the entirecontentsofthe‘Products’table:

To return only a selection of the columns, for instance ‘Stock’, we can use thefollowing:SELECTType,StockFROMProducts;

Page 92: Programming a Primer Coding Fo

Thiswillreturnthefollowing:

Type StockT-shirt 23Jumper 81Shorts 6T-shirt 2Trainers 29

Bothofthecommandswe’veusedherereturneveryrowofthedata,evenif—asintheexampleabove—weonlywantasubsetofthecolumnsavailable.Tofindparticularrows,wecanusetheWHEREclause,whichwillselectdatawhereacertaincolumnhasaparticularvalue.Inourclothingstore,forinstance,theownersmaywishtoseealistofthestock they have with the ‘Nike’ brand. They would use the WHERE clause to add arequirementthatthe‘Brand’columnoftherecordbeequalto‘Nike’.SELECT*FROMProductsWHEREBrand=‘Nike’

Whichwillreturnthefollowing:

Iftheclothingstorethenordersintenitemsofanewproduct,sixhatsfromPumaforinstance,theywillneedtoinsertanewrecordtothedatabase.Thiscanbedonebyusingthe‘INSERT’clauseasfollows:INSERTINTOProductsVALUES(6,‘Hat’,‘Puma’,1θ);

Whentheuserselectstheentiretableagainthenewitemwillappearinitsplace.SELECT*FROMProducts;

As new stock comes in, the ‘Stock’ column of a particular item may need to beupdated.Let’ssaythestorehasjustreceived100moreAdidasT-shirtsbringingthetotalinstockto102.Inthiscase,anotherclausecanbeusedandyes,you’veguessedit!It’sanUPDATEclause.

Thisstatementupdatesthetable‘Products’bysettingthe‘Stock’columntothevalue102 for all recordswhere the ‘Brand’ column is ‘Adidas’ and the ‘Type’ column is ‘T-

Page 93: Programming a Primer Coding Fo

shirt’.ThetablebelowillustratestheeffectofthisUPDATE.

Toremovearecordfromthedatabaseentirely,theownerofthesportswearstorecanusetheDELETEclause.

DELETEFROMProductsWHEREType=‘T-shirt’;

Hereweare tellingourSQLdatabase todeleteall records from the ‘Products’ tablewherethe‘Type’columnisequalto‘T-shirt’.SincetwooftheproductsareT-shirts,thisstatementdeletesbothoftheserecordsfromthetable.Byselectingtheremainingrecordsinthedatabasewecanseethatthey’rebeenremoved.

Wenowhaveabasicunderstandingofhowtomanipulatedatainarelationaldatabase,buthowdidweget thisdatabase there in the firstplace?Andhowdidwechoosewhatdatathetablecontained?It’swellworthnotinghowtocreateadatabaseandhowtoaddourowntablestoit.

Tocreateadatabase,weusetheCREATEDATABASEstatement:CREATEDATABASECustomerDatabase;

In the example above, we’ve simply created a database with the nameCustomerDatabase,butwecancallitwhateverwewant.Ifour‘Products’tablewasinadatabasecalled‘Inventory’,wecoulduseaSHOWDATABASESstatementtodisplayalistofallourdatabaseswhichwouldgiveusthefollowing:

Databaseinformation_schemaInventoryCustomerDatabasemysql

There are two surprising databases in here that you won’t have been expecting.‘information_schema’ and ‘mysql’ arebothdatabaseswhichhold information aboutourdatabases, specifically the particular SQL relational database that we’re using, and theprivilegesoftheuserswhocanusethedatabasesandtables.Ingeneralyoucanforgettheyexist.

Page 94: Programming a Primer Coding Fo

UsethekeywordUSEtotellthedatabasethatyouwanttouseaparticulardatabase.

Fromhere,we’reabletocreateatablewithinthe‘CustomerDatabase’databaseusingtheCREATETABLEstatement.CREATETABLECustomers

Thestatementabovecouldallbeononeline,butisseparatedforclarity.Thegeneralformat for thecreationofa table isclear fromthisexample.Wedefine thenameof thetable after the CREATE TABLE statement, in this case ‘Customers’, and specify thecolumnnamesanddatatypesofeachcolumninsidethebracketsthatfollow.Thenameofthe column is defined first, followed by the type of data being stored. Each column isseparatedbyacomma.Anumberofadditionalcommandscanbeusedinthedefinitionofeach columnwhich add specific requirements to the formatof thedata. In the exampleused above, the ID is an INT and the other columns are of typeVARCHAR(255). Aninteger in SQL can be considered the same as a Python integer— awhole number.AVARCHAR is aVARiableCHARacter fieldand thenumber255denotes that its lengthcannotexceed255characters.ItisessentiallyaPythonstring.

SQLinPHPSofar,ouronlyuseofSQLhasbeenbymanuallytypingintheSQLstatementstoretrieveourrequireddata.Inordertoautomatethisprocess,wecanspecifytheSQLstatementsinPHPandhavethemexecutedautomaticallyincode.

The following example shows a block of PHP code which connects to an SQLdatabase,preparesaquerytoexecute,executesitandfinallysetsavariableequaltothedatareturnedbythedatabase.

To explain— in PHP, themost common relational database isMySQL, a databasewhichusestheSQLlanguagetoqueryit.Wecanusethefunction‘mysql_connect’inPHPtoconnecttothedatabase.Inthiscase,we’reassumingwehaveourdatabaseonourlocalcomputer ‘localhost’, and are connecting with the username ‘username’ and password

Page 95: Programming a Primer Coding Fo

‘password’.Clearly there are some securityproblemswith thesecredentials,but for thepurposesofgettingusfamiliarwithSQLinPHP,let’sstickwithit.Theconnectionobjectisreturnedfromthisfunctionandislabelled$conforconnection.

The variable $sql is a stringwhich is initialisedwith the string ‘SELECT*FROMProducts’,whichisourquery.TheMySQLfunction‘mysql_query’isthenusedtoexecuteourqueryusingtheestablishedconnection,andthevariable$resultisgiventheresultintheformofaPHP‘resource’object.FinallytheconnectionisclosedandthePHPscriptterminates.

Thissameprocedurecanbeusedtoconnecttoanydatabase,accessanytableandtoautomaticallychangeitinanywayasrequired.Letusseeanexampleofhowwecanprintthecontentsofthe‘Products’tabletoaHTMLpage.

In theexampleabove,we’ve insertedaPHP ‘while’ loop intoouroriginalexample.The MySQL function ‘mysql_fetch_assoc’ accepts a ‘resource’ object — in our case‘$result’—andreturnsanassociativearray(similartoaPython‘Dictionary’object).ThisisthenextlineoftheSQLtable,whereeachelementofthearrayisarecord’scolumninthetable.Thisfunctionreturns‘false’assoonastherearenomorerowstoreturn.Inthe‘while’loopforeachrow,weprintastringdescribingthedatatypeandthevalueofthecorrespondingcolumninthedatabase,whichisaccessedbythenameofthecolumnasakey.

Whenthiscodeisexecuted,theresultisalistoftheentirecontentsofthe‘Products’table,displayedtotheuser’sHTMLpage.

Hopefully, theways thatPHPcanbeusedasascripting language tohandleauser’sinteraction with a server-side database throughweb applications are becoming clear to

Page 96: Programming a Primer Coding Fo

you.Therearecountlesspossibilitiesofhowthiscanbeusedintherealworldtocreatepowerful web platforms including social media websites, online work collaborationservices,contentdistributionservices,mediaentertainmentwebsitesandmanymore.

This part of your introduction to programming has been an extremely brief first-contactwithnetworks,sockets,HTML,CSS,JavaScript,PHPandSQL,andyou’llbynomeansbeproficient in these languages after this limited exposure; however you shouldnowhavesomeunderstandingofthebasicusesofeachoftheselanguages,aswellashoweachofthemisusedinthedevelopmentofaweb-basedsoftwareproduct.

Questions1. WhereisPHPcodeexecuted,ontheserverorclientdevice?2. WhatisthedifferencebetweenaGETrequestandaPOSTrequest?3. WhatSQLquerycanIusetoselecttheentirecontentsofanSQLdatabase?4. HowcanyouexecuteSQLstatementsfromwithinPHPcode?ConsidertheHTMLtags

andPHPfunctionsused.

Page 97: Programming a Primer Coding Fo

What’sOutThere?

Page 98: Programming a Primer Coding Fo

Chapter10

AmazingAlgorithms

Algorithms — sets of instructions that float between mathematical equations andcomputerprograms—havesaturatedour lives inalmosteveryarea,even ifwearenotawareofit.WhetherencryptingourcreditcarddetailstosendsecurelyovertheInternet,or taking us to a foreign destination as part of our satellite navigation system, the vastmajority of present day technology would not work without these highly sophisticatedprocesses.

Whenyouheartheword‘algorithm’,thereareanumberofresponsesyoumighthave.You might immediately understand what we’re talking about because you studiedcomputer science at university. Or you may know that companies like Google andMicrosoftusethemtodocleverthings,butyouarenotreallysurewhattheyare.Oryoumaybetemptedtorunawayinterror,becausethosefoursyllablesarealienandhostiletoyourears.Ifyoufallineitherofthelasttwocategories,thischapterisforyou.

Analgorithmisaconceptualsetofsteps,designedtosolveaproblemorreachagoalin an efficientmanner. In the context of computer science they are typically relativelysmallpiecesofcode,whichusedatainsomespecialwaytoproduceameaningfuloutput.

It’s important to understand the idea behind designing an algorithm and understandhowsomespecificalgorithmswork.Mostprogrammersaren’tdevelopingalgorithmsassophisticatedasthoseusedinacreditcarddataencryptionorforaGooglesearch,buttheywillneedtodealwithalgorithmsoftheirownonadailybasis.Inourcase,whencreating‘for’loopsandfunctions,we’rewritingourownalgorithms,andweneedtounderstandafewthatarealreadyouttheretohelpustowritepowerfulandeffectivealgorithmsofourown.

PageRankThebroad ideaofhowGoogle’ssearchalgorithmworkshasbeenpublicknowledgeformanyyears,despitethespecificdetailsofhowitorganisesitssearchresultsremainingacloselyguardedsecret.

The algorithm Google uses is PageRank. Before Google, search engines usedinefficientandineffectivealgorithmstoseekwebsites.Google’screationofthePageRankalgorithmrevolutionisedthesearchengineandGoogle’spopularitygrewmassively.

PageRankworksbylookingatallofthelinksontheInternetwhichpointtoacertainpage,andcountinghowmanyoftheselinksthereare.Alinktoapagecanbeconsideredavoteforthatpage’squalityorarecommendationtovisitit.Thismeansthatthemorelinksapagehaspointingtoit,thegreateritsPageRankwillbe.

Thisisingenious,butitisnottheendofthestory.PageRankaddsanotherdimension

Page 99: Programming a Primer Coding Fo

whichhastodowiththevalueofavote.Ifastrangeratthepubrecommendsaparticularrestaurant, itmay carry someweight and Imaywell go and check it out, however if aworld-renowned chef recommends a restaurant, his authority means that therecommendation will have a far greater value. This is similar to PageRank’s secondfeature.PageswithahighPageRankconferahigherPageRankthemselves.Ifafriend’sblogpointstomyblog,itwon’tcountformuchintermsofmyoverallPageRank.Butifthe highly rankedwebsite like theBBCorOxfordUniversity do, that has a far greatervalue,andthereforemyownPageRankisboosted.

Takealookattheillustrationonnextpage.Eachpageinthediagramrepresentsawebpage.ThenumbersonthepagerepresentthePageRankofthatparticularpage—i.e.theweight that that particular website has when ‘voting’ for another page. The arrowsbetween pages represent links to other pages, and the numbers by the arrows are theweightthataparticularlinkhaswhenlinkingtoanotherpage.

LetustakethepagewithID=1asanexample.Thereare4linkswhichpointtothispage,andtheircombinedweightgivesthePageRankof0.304.Sincetherearefivelinkson thispagewhichpoint toexternalpages, thePageRank isdividedbetween these fivepages,contributinganaverageof0.061tothePageRankofeachofthepagesithaslinksto.ThisisthebasicconceptbehindGoogle’ssuccesswithsearch.

There are numerous additional complexities that Google has added to its searchalgorithm,butGoogle’sinitialsearchfeatureremainsitsmostimportant.

SortingOneofthemostcommonoperationsneedingtobeperformedondatabyprogrammersissorting.Themostintuitivewaytoorderalistofitemsittofindthesmallestitemandputitfirst,thenfindthesecondsmallestandputitnext,andsoon.Thisalgorithmisrelatively

Page 100: Programming a Primer Coding Fo

slow,however,asthenumberofitems(N)inthelistincreasesthetimetakentosortthelistbyafactorproportionaltothenumberofitemssquared.

Fortunately, there are a great number of different sorting algorithms available thatworkmorequickly.Onesuchalternativeismergesort,whichusesa‘divideandconquer’approachtosorting.MergesortdividesalistwithlengthNintoNsub-listsandrepeatedlymergesthesub-lists,comparingthefirstelementsofeachsub-listtobemergedandthenplacingtheminthecorrectpositionuntilallofthesub-listshavebeenmergedintoasinglelist.

From the illustration above, we can see how merge sort works. The initial list isrepeatedlysplitintosub-listsuntilthereareNsub-lists.Thenconsecutivepairsofsub-listsaremergedintheirsortedorderuntilthelistisfullyreconstructed.

ShortestPathAlgorithmsforfindingtheshortestpathfromonepointtoanotherhavebeenstudiedforyearsandtherearemanyavailable.Thesealgorithmsareusedeverywhere,fromfindingthe best running route, to identifying the quickest way to get home from work, torecommendingthenearestplacetofindafastfoodrestaurantonaFridaynight.

ConsiderasummerSundayafternoonwhereyouareplanningarunningroute to thenext village.You’re unlikely to evaluate every possible route, since the universewouldhave suffered its heat death by the timeyou finished. In order to find the fastest route,quicklyandeffectively,amoreintelligentalgorithmisrequired.

One of the fastest algorithms for solving this path finding problem is known as‘Dijkstra’s algorithm’, named after the computer scientist EdsgerDijkstra. It is a fairly

Page 101: Programming a Primer Coding Fo

complexalgorithmwhich involves theuseofsomeunfamiliardatastructures. It’sbasedonthe idea thateverypathsegmenthasa‘cost’associatedwith travellingalongit.Thiscostisusuallyrelatedtothesegments’length,butitcanalsoberelatedtothe‘terrain’orthe‘traffic’.Theshortestpathisfoundbychoosingthepathswhichhavetheleast‘cost’,and provide the greatestmovement in the direction of the destination point.Using thisalgorithmtoanalyseacityofaround15,000segmentsofroadand8,000intersections,ittakesaboutonesecondtocomputeashortestpathbetweentwopoints.

Consider the map below. Try to use the idea of minimizing the cost (the numbersbetweenthepoints)getfrompointfivetopointone.

Formany applications, even this algorithm is too slow, somore efficient andmorecomplexalgorithmsareintroduced.Typicallyinthedesignofthesekindsofalgorithms,atrade-offcanbemadebetweenspeedandaccuracy.Ifanoptimalroutemustbefoundatanycost,alessefficientbutmoreaccuratealgorithmisrequired.Howeveriftheproblemathandcanbesolvedbyfindingapaththatis,say,10%longerthantheshortestpath,thenamuchfasterbutpossiblylessaccuratealgorithmcanbeused.

ArtificialIntelligenceSome of the most powerful and advanced algorithms are seen in the field of artificialintelligenceorAI.AIhas becomeabit of a buzzword in technology and calls tomindfilmslikeiRobot,depictinghuman-likerobotstakingovertheworld.IfaniRobotisevermanufactured, it will surely depend upon a huge amount of AI, but robotics is by nomeanstheonlyapplicationofthiskindofintelligentalgorithm.

Put simply, artificial intelligence is the capacity of a computer to exhibit thecomputationalbehaviourofhumans.InthefieldofAI,thecomputerwhichexhibitsthis‘intelligence’ isknownasan intelligentagent.This agent typicallyperceives somethingrelating to its environment and, based on this, makes decisions which enhance itsperformance.

Thisenvironmentmaynotbeaphysicalenvironment,butratheracontextinwhichitisdesigned tooperate, suchasonaserver toprocessuser-dataor inahandheldmobiledevicetounderstandauser’svoicecommands.

ThefieldofAIisparticularlyyoungandimmature.Thereareahostofapplicationsof

Page 102: Programming a Primer Coding Fo

AI in engineering, medicine, education, transport and communication that couldrevolutionise these sectors.While it is already having a substantial influence, somuchmorecanbedone.

ThecentralproblemsforAIresearchersistofindwaysforcomputerstoperformvery‘human-like’actions,suchasreasoning,planning,understanding,learningandperception.Trivialforthehumanmind,theseareincrediblydifficultforcomputerstoperform.

At present, no computer can fully exhibit full artificial intelligence (so as tocompletely simulate human behaviour). In some fields, such as assembly plants,computerscanhugelyoutperformhumansintermsofspeedandaccuracy,but,sofar,theyareonlycapableofperformingverylimitedtasks.

As we have seen, algorithms are fundamental in solving many complex problems.We’veonlytouchedonasmallsubsetofpopularalgorithmsthatyoumayendupusingatsomepoint.Manyareuniquetoaspecificproblemandyou’llneedtolearntobeabletobreakupproblems into thesteps required tosolve them.However,manyalgorithmsareavailableforcommonproblems—theyhavealreadybeensolvedforyou.Allyouneedtodoisfindwhereit’sbeendone,andthenborrowthecode.

Questions1. Whatisanalgorithmandwhataretheyusedfor?2. WhatinformationdoesthePageRankalgorithmusetorankawebsite?3. Howdoesthemergesortalgorithmusea‘divideandconquer’approachtosortitemson

alist?4. Whatmodernapplicationsdoesashortestpathalgorithmhave?Howcanitbeusedto

solverealworldproblems?5. How does Dijkstra’s shortest path algorithm chose which path to take when it

approachesajunction?6. Howcouldsomeformofartificialintelligencebeusedtosolveaproblemyoufaceona

dailybasis?

Page 103: Programming a Primer Coding Fo

Chapter11

ProgrammingLanguages,LibrariesandFrameworks

Afewyearsago,IsetmyselfthechallengeoflearningFrenchusinganaudioresourceIfoundonline.Needless tosay,I failed inachievingmygoals;howeverIdid learn thatIalready know a lot of French just by knowingEnglish.A lot ofEnglishwords share acommon origin with French words, leading to many similarities. For example, manyEnglishwordsthatendin-lysuchas‘absolutely’or‘intensely’haveequivalentsinFrenchendingwith-ment.‘Absolument’istheFrenchwordfor‘absolutely’and‘intensément’ istheFrenchwordfor‘intensely’.

Programming languages such as Python can be compared in somewhat comparableways.Theyhavesetsofunderstoodvocabularyandsyntaxstructures,andiftherulesofthelanguagearenotcorrectlyfollowed,thelanguagecannotbeunderstood.

We have already looked at a broad set of programming languages, includingJavaScript, PHP andHTML, so itwould not surprise you to hear that just as there aremanyhumanlanguages,therearealsomanyprogramminglanguages.Eachlanguagewasdesigned for a particular reason and each, therefore, has a particular purpose. Someprogramminglanguagesarebetterthanothersfordifferenttasks,andsomearecapableofthingsthatotherssimplydonothavethevocabularytodo.

Thischapterintroducesafewnewlanguages.Wewillnotbelearningthemhere,butratherfindingoutwhattheycando,andwhatsituationstheyarebestfor.Byknowingthenames of a few popular languages and by understanding both their capabilities andlimitations,youwillbefarmoreequippedtofindwhichistherightlanguagetolearnfortheparticularprogrammingchallengesyouface.

Modern development projects can usually be categorised into one of the followingcategories: ‘web’, ‘mobile’ or ‘desktop’ applications. Web applications are softwareproducts delivered across the Internet and viewed in a web browser, including socialmedia websites, online news applications and online forums. Mobile applications aredeliveredtomobiledevices,suchasphonesandtablets,andaredesignedspecificallyforthe smaller screen-size and hardware capabilities of such devices.Desktop applicationscanbethoughtofastraditionalsoftwarerunningonadesktopPCorlaptop,andexploitingthehighcomputationalpowerandlargerdisplaysizeofthesedevices.So,whatisthebestprogramminglanguagetogetyourdevelopmentprojectupandrunning?

WebIdeasWithmobiledevicesarebecomingmorewidespreadandapplicationsforoursmartphonesare being released all the time, new web based tools and start-ups are gaining in

Page 104: Programming a Primer Coding Fo

popularity. Ingeneral,apieceofsoftwarecanbedevelopedmorequicklyasawebappthanatraditionaldesktopapplicationandisalsomoreaccessible,somuchofthesenewapplicationsareprovidedaswebserviceshostedonaserver.

WehavealreadylookedatPHPasaserver-sidescriptinglanguage.NowwearegoingtolookatusingPythonontheserver-side.We’realsogoingtolookatalanguagecalledRuby.Withtheselanguagesyoucancreateanythingfromhotelbookingwebsites,tonichebloggingapplications,tonewonlinemarketplaces.

BootstrapWhenwelookedatHTMLandCSSwewereintroducedtothe<div>tagwhichwecouldstyle usingCSS.Bootstrap is a freeCSS framework developed byTwitterwhich helpsdeveloperstodesignbeautifulwebpagesquickly.t’sincrediblyeasytouse.ItrequiresnopriordesigningknowledgeandassumesthatallyouaretryingtodoiswritesomeflexibleandattractiveHTML.

Inessence,itisapre-writtenCSSstylesheetwithsupportforsomepopularJavaScripttools.AllyouneedtodoisplacetherequiredHTMLmark-upasattributesinthecorrectelement tags and you’re good to go. There are some fantastic tutorials for Bootstrapavailable online and if you end up needing a beautiful user interface for your webapplication,Bootstrapisthewaytogo.

JavaScriptandjQueryjQueryisapowerfulJavaScriptlibrarywhichimprovesandsimplifiesarangeofcommonJavaScriptactivities.Itprovidessimplemethodsforattachingeventhandlerstoelementsofapage—suchasbuttonsor<div>tags—toallowthemtobecomeinteractive.jQueryalsomakesiteasytogiveyourpagesimpleanimations.ItprovidesmethodsformovingHTML elements when an event occurs, making them fade away, slide around, changecolourorchangecontent.

jQuery also provides easy use of a feature known in JavaScript known as ‘Ajax’(AsynchronousJavaScriptandXML).Thisisaveryusefulfeaturewhichallowscontenttobe loaded fromaserverandsent toupdate thecontentsofapage,after thepagehasalreadyloaded.Itallowsforthecontentsofapagetobeupdatedwithlivedata,withoutreloading theentirepage. jQueryallows this featureof JavaScript tobeusedeasilyandrobustly,usingitsownAjaxmethod.TheAjaxfeatureofjQuerycanalsobeusedtomakeGET and POST requests, providing reliable, full-featured, and fully interactivecommunicationwithaserverafterawebpagehasalreadybeenloaded.

Forprovidinguserinteraction,simpleanimations,Ajaxandmore,jQueryhasalottooffer. It canbeeasilypickedupandwill saveyou timeandenergy, andwillultimatelygiveyouabetterresultwhenyouputyourideasintocode.

PythonandDjangoManydeveloperswouldrecommendthatPythonbethefirstlanguagelearntbyanovice,whichiswhyitisthelanguageonwhichthefirsttwopartsofthisbookarebased.Using

Page 105: Programming a Primer Coding Fo

onlineprogramminggames,Pythonisnowthelanguagethatmanyschoolsarebeginningtoteachtheirstudents.

Comparedtomanyotherlanguages,itisextremelyeasytopickupandthebasicscanbelearnedinafewdays.However,inordertobeareallyexcellentdeveloperyou’llneedtogofarbeyondthis.Fortunately,Python’ssimplesyntaxmakesiteasytodeveloplargesystemsmuchfasterthaniftheywerebeingimplementedinotherlanguages.

But,inordertodevelopawebapplication,Pythonisnotenoughbyitself.You’llneeda ‘web application framework’ in order to produce a robust and interactive webapplication using Python. A web application framework is an abstraction in whichsoftwareprovidinggenericorcommonfunctionalityisusedtominimisethetimeneededtodevelopanewapplication.Frameworksallowdeveloperstofocusonspecificpartsoftheirapplication,insteadofon‘repeatcodes’thatareusedeverywhere.Itallowsthemtocreateapplication-specificsoftwaremoreeasily.Thisalleviatesoverheadsassociatedwithcommonactivitiesperformedinwebdevelopment,byallowingdeveloperstowritecodethat’sunderstandable,manageable,secureandrobust,morequicklyandeasily.

Django is the most popular web application framework for developing webapplications in Python. It is free, and follows the Model-View-Controller (MVC)architecture.Thisisadevelopmentpatternwhichisintendedtoincreasethesimplicityofwebapplicationdevelopment.Itdoesthisbyseparatingthewaysinwhichinformationisstored, presented and accessed by the user into separate components. Data is stored asmodels,presentedusingviewsandaccessedusingcontrollers.

ThediagramonnextpageillustratesthebehaviouroftheMVCarchitecture.Auser’sbrowser requests thewebpageon theserverhosting thewebapplication.Theuser thenseesthe‘view’,whichisthepartofthewebapplicationthatincludestheHTML,CSSandJavaScript,which display the content clearly, interactively and aesthetically to the user.Thisissentfromthewebservertotheclient’sbrowser.

Whenauser interactswiththewebsite insomeway(suchasbysubmittingaform),theGETorPOSTrequestsentby theuser ishandledbyacontrolleron theserver.Thecontrollerunderstandstheuser’sinteractionwiththewebsiteandknowshowtohandleit.Ontheserver,thecontrollerthenaccessesmodelswhicharealsostoredonthewebserver.ThesemodelsrepresentthedatathattheuserisinteractingwithandareusuallylinkedtoanSQLdatabaseorsimilar.

Page 106: Programming a Primer Coding Fo

Fromhere, theview iskeptup-to-dateby responding to theuser’s formsubmissionandupdatingthewebapplication’smodels.Eachtimetheuserrequestsanewpagefromthe web application, the view is updated to display the most up-to-date models. Webapplication frameworks that follow theMVCarchitecture use this pattern to handle thewebapplication’sstorageandhandlingofdata.Itmakestheprocessofimplementinganddeployingaprototypewebapplicationmuchfaster.

Pros Cons

PowerfullanguageFastscriptingWidespreadusageandsupportEasytolearnManypre-writtenmodules

None

RubyandRailsRubyisaprogramminglanguagequitesimilartoPython.Itisascriptinglanguageandassuch its ownRuby interpreter. Its syntax sharesmany similaritieswith Python, and thelanguageisalsoveryeasytolearn.ToillustrateRuby,theexamplebelowshowsasmallRuby script which defines a ‘Person’ class, creates a Person and prints its instancevariables.

Page 107: Programming a Primer Coding Fo

RubyoffersafantasticMVCwebapplicationframeworkcalled‘RubyonRails’.Railsissimilar toDjangoin itscapabilities,structureandusage,and isextremelyeasy touseandunderstand.ThedocumentationforRailsisexcellentandyou’llfindmanybooksandonline tutorials thatwill takeyouthroughusing theapplication.FacebookisanobviousexampleofagreatwebapplicationusingPHP,howevertherearemanycompaniesthatareusing the Django or Ruby on Rails frameworks for their time-saving and usabilitybenefits.

Pros Cons

EasytopickupLargecommunityWiderangingfeaturesandcapabilitiesPowerful

None

MobileIdeasIfyour idea iswebbased,we’ve justseen twoofmanyfantasticframeworksforgivingyou the toolsyouneed tocreatepowerfulwebapplicationsquickly.WithBootstrap it’seasytomakeyourwebappavailableonmobiledevices,adjustingfortheirsmallerscreensizes and for touch screens. But Bootstrap is not sufficient.. Many ideas require thegraphics, computational power and sensors that are only available through newlydevelopedmobileapplications.

The two most popular mobile platforms are Apple’s iOS and Google’s Android.Microsofthasreleasedamobileoperatingsystem(OS)calledWindowsPhone8,butsofar it has not beenwell received.We’ll cover the language used onWindows Phone 8under‘DesktopIdeas’.

Traditionally,astart-upwouldneedtodevelopseparateapplicationsfortwoorthreeof these mobile platforms, but now there are a lot of cross-platform languages,frameworks and converters that make life easier, by developing cross-platformapplicationsquickly.ThefasteryoucanprototypeaMinimumViableProduct(MVP),thefaster your product will be able to be used. However, there are always restrictions orcompromisesthathavetobemadewhenusingcross-platformframeworksandoftentheyreducethequalityofwhateveritisyou’reproducing.

So,formany(ifnotmost)mobiledevelopmentprojects,itstillmakesalotofsensetodevelop applications separately on eachplatform.Let us look at someof the languagesyoucanuse.

Objective-CApple uses a language called Objective-C for most of the development done on itsdevices.TheAppleiPhoneisnoexception,sotodevelopaniOSapplicationit’sbest tolearnObjective-C. It’sa language thathasgaineda tremendousamountofpopularity inthe last few years. It is a general-purpose, object-oriented programming language, thataddsmanyadditionalfeaturestoalanguagecalledC.Objective-Cisprimarilydeveloped

Page 108: Programming a Primer Coding Fo

usingtheMacOSXapplicationXcodewhichisavailableforfree in theappstoreonaMac. It can be used to create all kinds of iOS applications including social networks,marketplacesandhigh-performance3Dgamingapplications.

The learning curve with Objective-C is a steep one and it is harder to learn thanPythonorRuby,butitisoneofthebestlanguagestolearntogetyourmobileappideaupandrunning.

ThecodeabovedemonstratesasmallObjective-Capplication.Thisexampleimportsthe‘Foundation’librarywhichcontainsthedefinitionofthe‘NSLog’functionandprintsthe sum of two integers to the screen. The ‘@’ symbol before the string inside theargument for ‘NSLog’ denotes the beginning of an ‘NSString’which is a special stringobject.Thelastlineofthisexamplereturnstheinteger0totheprocessthatexecutedthisprogram,denotingthesuccessfulcompletionofitsexecution.

TheuseofObjective-CforiOSapplicationdevelopmentcangetratherinvolvedanditmay take time for a beginner to get to grips with using the language— however theintegrateddevelopmentenvironment(Xcode)providedbyAppleisexceptional.TheiOSplatformisextremelyreliableandXcodeprovidesarangeofpowerfulbuilt-intoolstoaiddevelopment.Ifyou’reinitforthelonghaul,XcodeandObjective-Cprovideoneofthemostenjoyabledevelopmentexperiencesoutthere.

Pros Cons

GreatdocumentationGreatcommunityandsupportfordevelopersUsesApple’sdevelopmentlibrariesPowerfullanguagefeatures

SteeplearningcurveNotavailableonWindowsorLinux

JavaandEclipseJava is the primary language used to develop mobile applications for the Androidplatform.Itisarelativelyoldlanguage,butisstillverywidelyusedinanumberofareasof industry. It is generally considered a good programming language for beginners to

Page 109: Programming a Primer Coding Fo

learn,buthasasteeperlearningcurvethanPythonorRuby.WecouldhaveincludedJavaintheprevioussection,sinceitisalsoapopularserver-sidelanguageandhasitsownwebapplicationMVC framework, however it’s more commonly thought of as a mobile ordesktopprogramminglanguage.

The example above illustrates a very basic Android application written in Java. Itshows the syntax used for importingAndroid libraries, and how to define a Java class.Thisbasicprogramsimplycreatesa‘TextView’objectwhichislikeatextbox.Itsetsitstextusingthe‘setText’methodofthe‘TextView’objectanddisplaysitonthescreen.

ThesoftwaremostcommonlyusedtocreateAndroidapplicationsisEclipsewhichisafreedevelopmentapplicationwitharangeofpowerfulfeatures.Eclipseisavailableonallplatforms, includingWindows, Mac and Linux. This has obvious benefits in terms ofdevelopmentflexibility,butitdoesmeanthatthedevelopmentenvironmentprovidedbyGoogleforAndroiddevelopmentislessstableanddoesn’tofferthehigh-endqualityfordevelopersthatXcodedoes.

TheAndroiduserbaseisgrowingrapidly,asistheiOSuserbase,sotherearemanygreat opportunities available on this platform. If you’re looking to develop an app, butdon’t have access to anAppleMacBook for iOS development, thenAndroid is a greatalternative.

Pros Cons

PowerfullanguageRichlibrariesavailableGreatcommunityandsupportAlanguageforeverything

SteeplearningcurveDifficultsyntaxDifficulttouseforprototypingTimeinefficientdevelopment

Page 110: Programming a Primer Coding Fo

FreetouseExtremelypopular

DesktopIdeasMobile and web applications are without a doubt the most exciting platforms fordevelopingnew toolsand services in software.Due to theportabilityofmobiledevicesand thecross-platformnatureof theweb, thesemethodsofdelivering serviceshave themostpotentialtoshapeourculture,ourlifestylesandourmethodsofworking.Butthereare still a number of massive benefits to developing desktop applications, such asperformancebenefitsandtheabilityforthemtobeusedwhentheuserisoffline.

Increasingly, web languages such asHTML, CSS and JavaScript are being used todevelop desktop applications, such as Windows 8 apps. This presents an excitingopportunity for developers who are already familiar with these web technologies. Yetincredible innovation is still beingmade using themore traditional ‘compiled’ desktopprogramminglanguages.

C++C++(pronounced“Cplusplus”)isageneralpurposecompiledlanguagewithaproudandimpressivehistory.It’sbasedonthepopularcompiledlanguageC,hasbeenaroundsincethemid-1980sandisstillusedtodevelopawiderangeofapplicationsforthedesktop.Itsprimary uses now enterprise systems, performance critical systems and embeddedsoftware.Itisalanguagethathasmanybenefitsandfeaturesformultipleapplications.

The examplebelow is aC++programwhichprints ‘HelloWorld!’ to the commandline.

When executed, the ‘main’ function here is executed.The ‘<<’ is theC++ operatorincludedin‘iostream’forappendingastringtothecommandline.

In general, C++ is no longer the best option for developing interactive desktopapplications, but it’swellworth looking at if youwant to understand howmuchof themoretraditionalsoftwareweuseeverydayisdesignedandwritten.

Pros Cons

GeneralpurposeSimilartoJava

Steeplearningcurve

Page 111: Programming a Primer Coding Fo

C#Pronounced“Csharp”,thisisthelanguagetobeatfordevelopingalmostanyapplicationonWindows. It is a simple,modern, general-purpose programming language that is anevolutionoftheC/C++programminglanguages.

C# is the language touse forWindowsdesktopapplications,butalso itcanbeusedthroughMicrosoft’swebapplicationframeworkASP.NETtodevelopwebapplications.Itis also the primary language that applications for Microsoft’s Windows Phone 7/8platformsuse,soyoucanalsodevelopmobileapplicationsinthislanguage.

Here’sanexampleofabasicC#applicationwhichprints the text ‘Hello,World!’ tothe screen.We define a classwith the name ‘HelloWorld’ and a function calledmain()within it. When a C# application is executed, the main() function is executed. Thisfunctionusesthe‘System.Console’object’smethod‘WriteLine’toprinttexttothescreen.

YoumayhavenoticedthatthesyntaxhereisverysimilartoJavaandC++.Thismakesit easy to learnall three fordifferentapplications. Ifyoubecome familiarwith Java forAndroiddevelopment,you’llfinditeasytopickupC#.

Pros Cons

ModernandeasyGeneralpurposeUsedmobile,webanddesktopSimilartoJavaandC++

Older-stylesyntaxMediumlearningcurve

Questions1. WhatisBootstrapandhowdoesitmakewebdevelopmenteasier?2. WhatisjQueryandwhatareitsbenefitsoverstandardJavaScript?3. WhatisAjaxusedfor,andwhatprogramminglanguagedoesituse?4. What is Django? How would you best describe the benefits of using an MVC

frameworkforwebdevelopment?5. Whichprogramminglanguagescanyouuseforwriting iOSapplicationsandAndroid

applications?6. HowdothesyntaxandcommonusagesofC#andC++differfromeachother?Which

wouldyouusefordevelopingaWindowsPhoneapplication?

Page 112: Programming a Primer Coding Fo
Page 113: Programming a Primer Coding Fo

Chapter12

BigIdeas

Keepinguptodatewiththerapidlydevelopingtechnologyindustryisoftendifficult.Newproductsandservices,deliveringgroundbreakingtechnologyareintroducedtothemarketallthetime,soremainingaheadofthecurveinvolvesaconstantstruggle.

Muchofthisinnovationishappeningintermsofthedeliveryofnewproducts.Theseproductsarehardwareplatformsthatrequirenewapplications.Whileitistheproblemofelectronicengineerstoworryaboutcreatingthenextgenerationofhardware,andit’stheexperiencedcomputerprogrammerswhowillbewriting theoperating systems (OSs) torunonthem.Fortunatelyforus, thisinnovationisconstantlypresentingdeveloperswithnewkindsofopportunities.

Theintentionofthischapteron‘BigIdeas’intechnologyistopresenttoyouthemostimportant trends in the technologymarket, so thatyouarebetter able tounderstand theopportunitiesavailable.It’slikelythatmuchofthiswillbenewtoyouandyoumaywellfeeloutofyourdepth in thinkingaboutentering this competitivearena,but the truth isthatyoushouldfeelexactlytheopposite.

Asthetechnologyindustryisconstantlydevelopingthereareconstantopportunitiestojumponthebandwagon.Themajorityofthedevelopersandengineersinthissectorhavelittleexpertiseinindustriesotherthantheirown,andmanymorearenotabletosolvetheproblemsthatinterestthem,butareinsteadworkingonlarger(andmoreboring)enterpriseprojects.

Youasthereaderareaspreparedasanyexperienceddeveloper(andoftenmoreso)toidentifythemostimportantthingsyoudoatwork,home,school,oraspartofaclub,andto identify themost frustrating aspects aboutdoing them.Thenyoucan thinkof awaythese frustrations can be alleviated for you and others through software basedtechnologies.

Nodoubtwithfutureeditionsofthisbookthesetrendswillchange,howeverthefactremains that all of these areas are seeing growth at the moment. So let us see wheretechnology’stakingus.

CloudComputingThepoweroftheInternetisinthecapacityforfilesstoredonacomputer,onesideoftheworldtobeaccessedbyacomputeroncompletelytheothersideoftheworldinafractionofasecond.Thishasmeantthatfilesmaintainedbyorganisationsfromaroundtheworldare potentially available to everyone. Traditionally the Internet has been used to accessfilesbelongingtoanotherthroughtheirwebsite,whiledesktopcomputersorlaptopshavebeenusedtostorepersonalfilesbelongingtoanindividualuser.

Page 114: Programming a Primer Coding Fo

The term ‘cloud computing’ is everywhere, but few people feel they understandexactlywhat itmeans. In its simplest terms, cloud computing refers to the storing andaccessingofdataandprogramsontheInternet,insteadofonyourcomputer’sharddrive.YoumaybethinkingthatthatdefinitionisthesameasthedefinitionoftheInternet.Andyouhadberight.The‘cloud’isjustametaphorfortheInternet.

Whenyoustoredataorrunprogramsfromyourharddrive,that’scalledlocalstorageandcomputing.Yourdataandprogramsarephysicallyclosetoyou(onyourharddrive),soaccessing thatdata isquickandeasy.This isnot thecloud.Tobeconsidered ‘cloudcomputing’ a user must be accessing data or running programs over the Internet. Thismeansthattheprogramsandfilesthattheyarelookingforarestoredonaremoteserver,andaccessedoverthenetwork.Cloudcomputingopensupahostofpossibilitiesforusers,byallowingmultipleuserstoaccessthesamedataovertheInternet.

Forprogrammers, cloudcomputing is oneof themost excitingdevelopmentsof thetechnology industry, because it provides the infrastructure uponwhich software can bewritten to solve previously unsolvable problems. These include allowing formulti-usercollaboration; remote storageof personal documents to enable access fromany Internetenableddeviceintheworld;livevideoconferencing;onlinewordprocessing,spreadsheetandgraphicssoftwarewhichalleviatetheneedtoinstallsoftwarelocally;andmuchmore.

Platforms and tools for developers such as the Google Cloud Platform, MicrosoftAzure, Dropbox API and Amazon Web Services give developers the opportunity toproduce software solutions for problems faced by people all over the world, and caninstantlygetthemintothehandsofthosethatneedthemmost.

BigDataThe amount of information being collected and stored is increasing exponentially.Although the computational power of computers is also getting bigger, computers areincreasinglyunabletostoreandprocessdatalocally.‘Bigdata’isatermusedtodescribesets of data which are so large and complex that it becomes difficult to process usingpersonalcomputers.

Ahugeamountofdataisnowpubliclyavailable.Wikipediahasgivenusaccurateanddetailed knowledge of anything we can think of. Twitter produces millions of publicTweets per day which tell us all sorts of information about people and their opinions.Census data,weather data, stockdata andmuchmore are all available to theworld forfree.

Organisations are also able to collect data from their customers. This includes theircustomer’sactivityontheirwebsite,address,age,purchasinghistoryandmore.Datasuchas this is valuable to companies to improve the quality of customer service, to createtargeted advertising, tomanage email correspondence, and to plan for company growthandminimiseexpenses.

Bigdata is changing theway thatwedo life anddobusiness, and it’s changing thewayweworktogether.

Its use by an organisation leads to a competitive advantage through high quality

Page 115: Programming a Primer Coding Fo

customerfeedbackandmarketingcampaigns,andbetterstrategicdecisionmakingthroughhavingmoredataaboutwhichdecisionwouldproducethebestoutcome.

Theopportunitiesherefordevelopersareintheareasinwhichbigdatacanpositivelyimpactourselvesorothersaroundus.Ifyou’reateacher,bigdatacanbeusedtoanalysethe correlation between various teaching styles and student exam results. If you’re asociologist,youwillbeabletousebigdatatoanalyseifthereisacorrelationbetweenahappy childhood and a successful career. If you’re a scientist, you can use big data tomeasure the link between alcohol consumption and the likely development of certaindiseases.

Forentrepreneurs,bigdataisperhapsoneofthemostvaluableideasoutthere.Valueisadded to rawdatawhen it iscombinedwithotherdataandanalysed.Companiesandorganisationsarealwayslookingforinnovativeinsightsintothemeaningofdata,andyoucouldbuildthestart-upthatprovidesthemwiththerighttool.

ThemostpowerfultoolfordevelopersinthisarenaisApacheHadoop.Thisisanopensourceframeworkforprocessinglargeamountsofdatainmultiplestoragelocations.Itisa complex framework and will take some degree of learning before it can be usedeffectively, but formany applications it can provide themost powerfulmechanism foraccessing and processing the data you need, to solve the problems you have set out toconquer.

TheInternetofThingsFormost of us in theWesternWorld, our lives andhomeshavebecome saturatedwithdevicesandapplianceswhichseektomakeourliveseasierandmoreenjoyable.Kitchenand living room appliances such as dishwashers, ovens, televisions and central heatingsystemsareallboughttoreducethetimeordifficultyassociatedwithcleaning,cooking,accessingentertainment,heatingourhomesandmore.This is testimony to the fantasticdevelopments in technology and has freed up time for us to domore of the thingsweenjoy.

MoreandmoreofthesedevicesarebecomingInternetenabled.Ourphones,laptops,tablets and televisions are now more often than not wired-up to the web, offering usservicespreviouslyunavailable.

‘The Internet of Things’ is a term used to describe the network of devices andappliancesthatarealreadyconnectedtotheInternet,andthosethatwillbe.Alreadysmartthermostats are allowing our central heating systems to be controlled from our phones.Locksforourhomesandcarsaregettingsmarter,andareincreasinglyaccessiblethroughourphonestoo.MoreandmoredevicesarebeingredesignedwithInternetaccess,inordertoincreasetheutility,accessibility,easeofuseandsecurityofourphysicalassets.

It would not be long before our beds, lighting, curtains and windows will becontrollableovertheInternet,andthispresentsdevelopersinallwalksoflifewithanotherarenainwhichtoexercisetheirimaginationandcreativity.

SecurityandDataPrivacy

Page 116: Programming a Primer Coding Fo

Inmanyareasoflifebenefitsgohand-in-handwithrisksandthisisnolesstruethanintheprogressoftechnology.Basicriskmanagementtellsusthatriskisrelatedtotwofactors,theprobabilityofanundesirableeventoccurringandtheextentofthedamagethatwouldensueshouldthateventoccur.Ifaneventislikelytohappen,butitsconsequencesarenotrelevant;thereisalowrisk.Similarlyifthereisahighlyundesirableconsequenceofaneventoccurring,yetanegligibleprobabilitythatitwillhappen,theriskislow.Howeveras theprobabilityand theconsequenceofavulnerabilitybeingexploitedcreepup, risksareincreased.

Cloudcomputingandwebtechnologiesareleadingtothecentralisationofmoreandmore of our everydaydata and services. It is often advantageous for an organisation tohaveitsactivitiesincreasinglyautomatedandcentralised.ThistypicallyinvolvesexposingcapabilitiestoInternetusers,somemalicious.Whethertheyaresecureornot,thereisnoquestion that the consequences ofmodern computer systems being attacked by hackershave increased massively in recent years, since the amount of control over data andphysicalinfrastructurethatcomputershavehasincreasedsomuch.

In addition, new technology is created all the time. There is no question that ascomputer systems are tested for security, improvements are made tomake the age oldsystems more secure. However new software, websites, services and Internet enableddevices are coming tomarket almost daily andmost undergo insufficient security testsbeforebeingcommerciallyreleasedandtrustedbycustomers.

Thisprovidesanevergrowingattacksurfaceformalicioushackerstouseinordertogainaccesstocriticalsystemsandexploitunknownvulnerabilities.Computersecurityisalreadyamulti-billiondollarindustryandwillonlyincreaseastechnologyimproves.Weshouldexpect toseesignificant increases inhighprofilesecurityvulnerabilitiesexposedandit’simportantnowmorethanevertoensurethattheprogramswedeveloparesecure.

NewLearningStylesMuch progress is being made in the delivery of education, and the availability ofknowledge,throughtechnology.WebsitessuchasUdemy,Coursera,TheOpenUniversityandiTunesUarehelpingtodeliverhighqualitydegree-levelcoursesforfree.Theyallowindividuals to choose for themselves the subjects to learn and avenues of learning tofollow,Usually,thereisnofeetopay.

Wikipedia and other knowledge sharing websites have changed the way we accessinformation.Books,webpages,videotutorials,quizzes,flashcardsandmemorygamesonalmosteverytopicareallovertheweb,andformanyofustheyareincreasingourskillset,ouremploymentprospectsandourunderstandingofthemostimportantthingsinlife,helpingustolearnefficiently,thinkcriticallyandworkeffectively.

Incountrieswhereeducationislimitedandadequateteachersarefewandfarbetween,technologyisincreasingaccesstoknowledgeforculturesthatdesperatelyneedit.Apoorunderstandingofwhatconstitutesahealthydiet,oralackofunderstandingaboutacurefor a known medical condition, can be a matter of life and death. Basic delivery ofeducation through new learning styles has the capacity to revolutionise healthcare,farming,economicgrowthandsustainabilityincountrieswithouttheeducationalheritage

Page 117: Programming a Primer Coding Fo

manytakeforgranted.

New learning styles are appearing regularly due to advances in technology and thistrendwill certainlycontinue.Nooneknowswhatour schools,universities and librarieswilllooklikein50yearstime,buteachofuscanplayapartinsolvingtheproblemsweseeineducationbydevelopingnewtoolsforlearning.

3DPrintingOne of the primary factors slowing the rate of progress in industry is the speed of theiteration cycle of prototyping newproducts— that is,manufacturing.Manufacturing isslow, expensiveand limited in itsdesigncapabilities and the shapes it canproduce.3Dprinting is the new hot topic in this field. It’s a way to produce rapid prototypes ofcomponentsbyprintinglayersofafinepolymerontopofeachother.Thistechnologyisstillinitsearlystagesandcommercial3Dprintersareonlyrecentlybecomingavailableataffordable prices. But this makes it a hugely exciting time for anyone involved inmanufacturing,teachingorart,whocanusethisnewtechnology.

Weshouldexpect3Dprinterstobecomemoreandmorewidespreadintheirusageandsoonbeintroducedintohomes.Thiswillenableuserstomanufacturetheirownproductsinsteadofordering them, leading toanumberofpotentialdevelopments insoftwarefordesigning3Dproducts,aswellasvirtualmarketplacesforvirtual3Dproducts.

WearableTechnologyandNo-TouchInterfacesFromthemomentofthereleaseofthefirstAppleiPhonein2007,developersallaroundtheworldbegantorealisetheopportunitiesthatsmartphonetechnologywouldpresent.Abrand new platformwith fantastic support for developers, and the new accessibility ofexcellent hardware and sound operating systems (OSs), has been a gold mine forentrepreneurs. Even now Apple, Google andMicrosoft are improving the support andcapabilitiesofferedtodevelopersopeningupnewdoorstosolvingpreviouslyinaccessibleproblems.

Doyouwanttoknowwhatthenextbighitintechis?Fromthesectionheaderyou’veprobablyalreadyguessedit,butifIcouldputmoneyonthenextplatformtoshakeupthesoftwaredevelopmentindustryitwouldbewearabletechnology.Youcan’tputmoneyonit,notintheprimarysenseatleast.Butthat’snottosayyoucan’tbetonit.

AndroidWear,anewOSforAndroidsmartwatches,hasalreadyhitthepublicdomainand developers are beginning to produce applications which exploit the inherentcapabilitiesofwearabletechnologybymakingnewapps.

‘No-Touch’istheideathatsmartdevices,particularlywearabledevices,arebestsuitedto be operated without the use of touch. That’s not to say they shouldn’t have touchscreens or an on/off switch, but the focus is on a devicewhich responds to the humanvoiceinanintuitiveway.Thismakesarangeofactivitiespossible,suchasgettingworkdoneinthecarwithouttakingyoureyesofftheroadoryourhandsoffthewheel.Itmakesitpossibletoseta timerfor theovenwhileyourhandsarecoveredinflourandeggsorchangethemusictrackyou’relisteningtowhilecyclinghomefromwork.

Page 118: Programming a Primer Coding Fo

By combining the programming capabilities of developerswith the frustrations youfaceeachday,eachandeveryoneofusisempoweredtouseourimaginationtodreamupwaystoreducethosefrustrationsandmaximiseutility.

Questions1. Whatiscloudcomputingandhowcanitimproveproductivityinbusinesses?2. WhatistheprimaryvalueofBigData?Whatexamplescanyougiveaboutinteresting

datathatcanbeextractedfromit?3. What are the primary security considerations that are involved with the Internet of

Things?4. Trytocomeupwiththreewaysthatcomputertechnologycanbeusedtoaidlearningin

developingcountries.5. How will 3D printing technology improve our design and manufacturing industry?

Whatpossibilitiesarethereforusing3Dprintinginthehome?6. Whatbenefitsdoeswearabletechnologyhaveintermsofusability,safetyandtechnical

capabilities?

Page 119: Programming a Primer Coding Fo

Chapter13

WheretoGofromHere

Ifyouhavemadeittothispartofthebook,‘Congratulations’!We’vecomealongwayinourjourneyoflearningtoprogrampracticallyforlife.Letusquicklyglancebackatwhatwehavecovered.Wehave

Lookedatunderstandingwhatprogrammingisandhowpracticalitcanbe,Understoodtheideabehindusingvariablestostoredataandoperationstomanipulateit,Developedanunderstandingforwhatan‘If’statementdoesandwhat‘for’and‘while’loopsareusedfor,Learned about methods and objects and how they can be used to model real worldobjects,MadeaGraphicalUserInterfaceusingwxPython,LearnedaboutnetworksandwebdevelopmentusingHTML,CSS,JavaScript,PHPandSQL,Discoveredtheusesofeachmajorprogramminglanguage,Beenintroducedtosomepopularalgorithms,Andhadaninsightintothedirectionthattechnologyisheading.

That isa lotofstuff tocover in less than200pages—for instance, there isahugeamountabout the languageofPython thatwedidnot cover.Now thatyouhavedippedyourtoesintotheworldofprogramming,itismysincerehopethatyouhavebeeninspiredandmotivatedtotakewhatyou’vealreadygraspedontothenextstage.Ifthatisthecase,youcandotwothingsfromhereon.Theyare(1)learn,and(2)do,andtheygohand-in-hand.

LearnItwas never the intention of this book to be a comprehensive guide to all things code.NeitherwasitintendedtobeatextbookonPython,butratheraverybroadexplanationofpracticalprogrammingworkedthroughfromthegroundup.Programmingcanbeaveryabstract discipline and much of what we have covered is simple for the experienceddeveloper,butcomplexforthenovice.Thisbookhasattemptedtoapproachthoselearningchallengeswith clear descriptions, illustrations and examples, in order tominimise thepainoflearningtocode.

Thismeansthatthereisagreatdealmoreworktobedone.Thebestplacetostartistogetmore familiarwithPython.Asyou’ve seen, it’s a language fit for purpose and it iseasy to learn.Therearemanyresources,bothonlineandonpaper thataregearedup to

Page 120: Programming a Primer Coding Fo

helping you get familiar with Python. Find a book with a comprehensive set ofexplanationsaboutallofPython’sfeatures,andworkthroughsomeexamplesyourselfinordertogetmorefamiliarwiththeprinciplesyouhavebeenintroducedtoalready.

DoOneof thebestwaysto learnis todo,andthis isparticularlytrueforprogramming.Aswellasusingexamplesinatextbookoronlinetutorial,startworkingonyourownproject.Itdoesnothavetobelargeordifficult,butifyoucanfindaprojectofyourownthatyoucareabout,youcanmakeityoursanduseitasaproductiveandenjoyablewaytodevelopyourprogrammingskills.

Hereisafewexamplesofprojectstogetyoustarted:

1. Make an attractive and informative website for your organisation, family business,churchorsocialclub.Ifnoneoftheseapplytoyou,doitforsomeoneelse’s.

2. MakeagameinPythonorJavaScriptforyoutoplayandsharewithyourfriends.3. Writeacommand-linePythonscript toautomatesomething thatyouoftenhave todo

manually.4. Make an app for your iOS or Android smartphone for your company, so generate

marketexcitementandattractcustomers.5. WriteaPHPscripttostoreemailaddressesinaMySQLdatabasewhichusersenterona

website.Youcoulduse this for a familynewsletter,wedding invitationwebsiteor anorganisation’smarketingcampaign.

6. Write a HTML and CSS website for a friend who sells homemade artwork, bakery,knitwear,embroideryorjewellery,andputpicturesoftheirproductsonit.

7. Get in touchwitha localplumber,puborcafewithanunattractiveordifficult tousewebsiteandoffertoredesignitforthemfreeofcharge.

8. Makeitafamilyprojectandaskyourkids,spouseorparentstomakesomethingwithyou.

Thesatisfactionofcreatingsomethingfromnothingwithyourownfingersusingcodeishugelyrewardingandonethat,ifyouarenotcareful,cangetaddictive.Themoreyoulearn, and the more you see others using what you have made, the more rewarding itbecomesandthemoreyouwillwanttokeepimprovingandkeepcreatingbettermobile,webanddesktopapps.

Someofyoumayhavebeensoinspiredbytheexcitementofprogrammingthatyouwant to pursue amore formal line of education and Iwould thoroughly recommend it.Findthebestschooloruniversitythatyoucangetyourselfintoandsoakupeveryiotaofinformationthat’sthrownatyou.

Ifyouuseyourmindandcommityourselftoaproject,maybeyouwillbethepersonbehindthenextbilliondollarInternetstart-uporthecreativegeniusbehindaninnovativelifesavinghealthmonitoringapplication.Itcouldbeyouwhocreatesawebapplicationforanewdecentralisednewsservice,oraninteractivetabletapplicationformoreeffectively

Page 121: Programming a Primer Coding Fo

managingpersonalfinance.Bigideasarenothardtocomeby,buttheyarehardtomakeareality.Ifnothingelse,learntouseprogrammingasatooltohelpyoumakeadifferenceintheworldweliveinandsharetogether.

Page 122: Programming a Primer Coding Fo

Afterword

Thankyouforreadingmybook.Youhavespentagooddealoftimeworkingthroughit,andIhopethatinreturn,you’vegainedagooddealofinsightintothebasicideasbehindcomputerprogramming.

IhopethatonedayIwillhavetheprivilegeofmeetingyouandhearinghowyouhaveenjoyedreadingmybook.Keepme informedaboutwhatyouare learningandcreating.Neverstopusingwhatyoulearntobuildapplicationswhichimprovethelivesofthoseinyourlocalcommunityandaroundtheworld.

TomBell

[email protected]

www.codingforbeginners.co.uk

Page 123: Programming a Primer Coding Fo

AppendixA

PythonDevelopmentEnvironment

In order to write and execute programs we need to setup our Python interpreter anddevelopmentenvironment.ThepurposeoftheinterpreterhasbeenexplainedinChapter1,anditallowsthecodewewriteinPythontobeunderstoodbythecomputerbytranslatingit into machine code. A development environment is the phrase used to refer to theprogramweuseinordertowriteourcode.

Forsimplicity,wewillusethedevelopmentenvironmentwhichisprovidedalongwithourPythoninterpreter,suchthatwhenweinstallourinterpreterwewillalreadyhaveourdevelopmentenvironmentsetuptoo.

InstallingthePythonInterpreterPython is open-source, meaning it is free to use and can be used in anyway the userwishes. Follow these steps in order to get your Python interpreter and developmentenvironmentupandrunning:

1. Using your browser (Google Chrome, Firefox, Safari or IE), navigate tohttp://www.python.org/download.Nearthetopofthepageyouwillseedownloadlinksfor Python 3.4.* and Python 2.7.8 (* will be the most recent version of Pythonwheneveryouviewthispage).

2. I recommend downloading Python 3.4.* since it is the most recent version and youshouldbecomefamiliarwithit.YoumayfindthattherearecompatibilityproblemswithPythoncodeyoufindonlineandthisversion,butingeneral legacycodewillworkinPython3.4.Clickonthedownloadlinkandnavigatetothebottomofthepagewhereyou will find a table of download links. Click the link that corresponds to yourcomputertype(i.e.WindowsorMacOSX)anddownloadit.

3. Findthelocationoftheinstalleryouhavejustdownloadedanddoubleclickittorunit.Hereyoumayhavetoclick‘Run’or‘Yes’toconfirmthatyouaregivingtheinstallerpermissiontorun.

4. Once thesetupwizardhas launched,youshouldclick ‘Next’ foreveryoption,unlessyouhavespecificreasonsnotto.

UsingthePythonShellYourPythoninterpretershouldnowbeinstalled.We’llbrieflyrunthroughtheoperationofthePythonShellandIDLE(ourdevelopmentenvironment)andverifythattheinterpreterhasbeensuccessfullyinstalled.

Page 124: Programming a Primer Coding Fo

Asnoted, theprogramthatwewillbeusingtorunPythoniscalledIDLE.Ifyou’reusingaMac,IDLEshouldbelocatedinyourApplicationsfolder.OnWindows,itwillbeaccessiblefromtheStartmenuinafoldernamed‘Python3.4.*’.

WhenyoufirstopenIDLE,you’llbepresentedwiththePythonShellasshownbelow.

This is used to execute Python commands straight away, line-byline. The followingdemonstratesitsusewithshortsequencesofmathematicalcalculations:>>>2+3*(4–1)

11

UsingtheIDLETextEditorForthemajorityofprogrammingneeds, itwillbemostappropriatenot torunprogramsline-by-lineusing thePythonShell,but tocreateacompletedocumentcontainingallofyourPythonsourcecode.IDLEcomeswithatexteditor,whichyoushouldalreadyhaveinstalled.

FromwithinIDLE,gototheFilemenuandclickon‘NewWindow’.Youshouldbepresentedwithablankdocumentasshownbelow.

Page 125: Programming a Primer Coding Fo

ThisiswhereyoucanwriteyourownPythonprograms.You’llneedtosavethisfilebefore running it,andensure that thefilenameyouhavechosenendswith‘.py’so thatyourcomputerknowsitisaPythonprogram.

Fromhereyoucanrunanycodefromthisbookbysimplycopyingwhatyouseeintothetexteditorandsavingit.Inordertorunyourprogram,simplygototheRunmenuandpress‘RunModule’.TheoutputwillappearinthePythonShell.

Page 126: Programming a Primer Coding Fo
Page 127: Programming a Primer Coding Fo

CommonProgrammingTerms

*(asterisk):Acommonsymbolusedinprogramminglanguagesformultiplication.

\(backwardslash):Acommonsymbolusedinprogramminglanguagesfordivision.

—(dash):Acommonsymbolusedinprogramminglanguagesforsubtraction.

/(forwardslash):Acommonsymbolusedinprogramminglanguagesfordivision.

Algorithm:Asequenceofinstructionsintheformofpseudo-codeorcodewhichisusedtosolveacomputationalproblem.

Array:Adatatypeusedinmanyprogramminglanguagesasanorderedcollectionofdatawhichcanbeaccessedbyspecifying theelementof thearray that is required.TheyaresimilartothelistdatatypeusedinPython.

ArtificialIntelligence(AI):Apopularand importantaspectofcomputersciencewhichseekstoimitateandreplicatetheintelligenceofhumanbeingsusingcomputersinordertosolvecomplexcomputationalproblems.

Bigdata:Animportantandpowerfulconceptincomputersciencewhichunderstandsthepowerofanalysinghugedatabasesinordertoextracthigh-levelmeaningfulstatistics.

Booleandata type:A commondata type used inmanyprogramming languageswhichcanhavethevalueTrueorFalse.ConditionalexpressionsaretypicallyevaluatedtobeaBooleanandareusedinconditionalstatementssuchasthe‘if’statementinPython.

Bug:Anerrorinaprogramwhichcausesittofunctionincorrectly.Bugsmaybedifficulttofindastheymayonlybecomeapparentwhenaprogramisinaveryrarestate.Theyarealsooftendifficulttoremove.

C:Apopularfunctionalprogramminglanguagewhichusesthecurlybracketsyntax.

C++:Anobject-orientedgeneralpurposeprogramminglanguagewhichusescurlybracketsyntax. Ithasasimilarsyntax to theCprogramming language,butwithobject-orientedfeatures.

C#: A popular object-oriented language developed by Microsoft as part of the .NETcollection of languages. It is a popular language for Windows development anddevelopmentonWindowssmartphones.

Class:Thedefinitionofanobjectwhichactsasatemplate,specifyingthevariablesandmethodsthatanobjecthas.

Code:Anabbreviationofsourcecode.

Comment: A line or block of text in a source code file which is used to explain theoperationofpartsofaprogram.Commentsareignoredbyaninterpreterorcompilerandareusedonlybydevelopersforclarifyingordescribingasectionofcode.Theyarealsooftenusedtoproducetitlesor‘readme’contentatthetopofasourcecodefile.

Compiler:Aprogramwhich turns the source codeof a programwritten in a compiled

Page 128: Programming a Primer Coding Fo

language, such as C or C#, into machine code which can be directly executed on acomputersCPU.

Constant:Aprefix toadata type inmanyprogramming languageswhichspecifies thatthevariablesvaluecannotbechanged.

Cross-platform: A term used to describe a propertywhich some programs have to becompiledandexecutedonmultipleoperatingsystems.

CSS:CascadingStyleSheet.AformatforspecifyingthestylisticfeaturesandformattingofpartsofaHTMLwebpageaccordingtothetags,classesandidattributesusedintheaffectedHTMLelements.

Data type: A term used to describe the kind of data being stored as a variable in aprogramminglanguage.Examplesincludeintegers,strings,listsandBooleans.

Debug: An activity employed by programmers which seeks to remove unwanted bugsfromaprogram.

Editor:Alsoknownasatexteditor.Aprogramusedonacomputertocreateandeditthecontents of a source code file. Many text editors provide additional features, such assyntaxhighlightingandbuilt-inconsoles.

Executablefile:A filewhich contains themachine codeof a program that has alreadybeencompiled.

Forloop:Afeatureofmanyprogramminglanguageswhichallowsablockofcodetobeexecuteda setnumberof times.Theycanbeused to iterateoverelementsofa list anyimplementloopsincustomalgorithms.

Function: A subprogram within a program which performs a specific task within acomputationalsystem.Functionsoftenacceptparametersandreturnanoutputvalue.

GUI:AGraphicalUserInterface,definedincodeandusedtodisplaycontenttotheuserandprovideanintuitiveinterfacethroughwhichausercaninteractwithaprogram.

HTML: HyperTextMarkup Language. A mark-up language used primarily in websitewhichspecifiesthelocationsofcontentwithinawebpage.

ifstatement:Afeatureinmanyprogramminglanguageswhichallowsdifferentblocksofcodetobeexecutedunderdifferentcondition.

Infiniteloop:Asituationinwhichaloopinaprogram,suchasa‘for’loopora‘while’loopisunabletoexitbecausetheconditionrequiredforittofinishcanneverbemet.Anexampleisa‘while’loopinwhichtheconditionoftheloopalwaysevaluatestoTrue.

Inheritance:A feature inmanyobject-orientedprogramming languageswhichallowsaclasstouseallofthevariablesandmethodspredefinedintheclassbeinginheritedfrominordertosimplifythedesignofsimilarclasses.

Input:Afinitesetofvariableswhicharegiventoaprogram,ormethodat themomenttheyarecalled.Inputteddata is typicallyprocessedandformsthebasisofsomekindofoutput.

Integer: A numerical data type used inmany programming languageswhich can store

Page 129: Programming a Primer Coding Fo

positiveandnegativenumberswithnodecimalplace.

Java:Acommonobject-orientedgeneral purposeprogramming languageusedon somewebsites,desktopapplicationsandAndroidapplications.ItisverysimilartoC#andC++initssyntax.

JavaScript: A web scripting language used in front-end web pages to handle userinteractionwithawebpageandalsotomanageanimationsandothergraphicaleffects.

Linux:Apopularopensourceoperatingsystemusedprimarilybyprogrammers,scientistsandinembeddedsystems.

Machinecode:Acollectionofbinaryinstructionswhichhavebeencompiledsoastobeable to be understood by aCPU and executed in order to perform some computationaloperation.

Method:Asubprogramwithinaclassorobjectwhichperformssomekindofdataontheinstancevariablesofthatobjectandtypicallymodelsomekindofrealworldbehaviour.

Object-oriented programming: A programming paradigm in which a programminglanguage represents the idea of objectswhichmodel a realworld object or system andcontaindataabouttheobjectaswellasmethodswhichactuponthatdata.

Output: A finite set of variables that are returned from a program or method, or aredisplayedtoauserwhichhavesomekindofmeaning.Outputsareoftentheresultofsomekindofcomputationoninputdata.

Opensource:An initiativewhich seeks toprovidehighqualityprograms, libraries andframeworks to developers for free and without restrictions on their use in order tomaximisetheproductivityofprogrammersandtheirspeedofdevelopment.

Operatingsystem:Acomplexprogramwhichisexecutedwhenacomputationaldeviceis turned on and provides a stable environment in which additional programs can bedeveloped and executedmore easily. Operating systems often provide features such asmulti-threading, synchronisation, resource management, network management, securityandpowermanagement.

PageRank:AnalgorithmdevelopedbyGoogleinordertoscorewebpagesaccordingtotheirrelevancy.Apage’sscoreisbasednotonlyonthenumberofwebsiteswhichpointtoit,butalsoonthescoreofthosewebsitespointingtoit.

Parameter:Avariablewhichispassedintoafunctionofmethodwhenitiscalled.Alsoknownasan‘argument’.

Parameterlist:Alistdefining thedata typesandvariablenamesofparameters thatareacceptedbyafunctionormethod.

Perl:Apopularinterpretedprogramminglanguageusedprimarilyinwebapplications.

PHP:Aserver-sideinterpretedscriptinglanguageusedprimarilywithwebapplicationstohandle user requests and to provide interaction with databases and other server-sideresources.

Python:Apopularprogramminglanguageusedprimarilyinwebapplications.

Page 130: Programming a Primer Coding Fo

Socket:Aprotocolforprovidinglow-levelbidirectionalcommunicationbetweenaclientandserveroveranetwork.

Sorting: A computational task of arranging sets of variable in some kind of order asrequired, such as alphabetical order or numerical order.A range of algorithms exist forprovidingthisfunctionalityeachwithvaryingdegreesofcomputationalefficiency.

Source code: A term used to describe the contents of the file containing a completedescriptionofaprogramwritteninaprogramminglanguage.

String:Adatatypewhichstoresasequenceofcharacters.

SQL:StructuredQueryLanguage.Aqueryinglanguageusedtoqueryrelationaldatabasesinordertocreate,read,updateanddeletedata.

User interface: A term used to describe a graphical interface provided by a programwhichallowsuserstoviewdataandinteractwithit.

Variable: A packet of data stored in a program which holds data important to theoperationofaprogram.Variablescanbechangedduringtheexecutionofaprogram.

Whileloop:Afeatureofmanyprogramminglanguageswhichenablesablockofcodetobeexecutedrepeatedlywhileacertainconditionistrue.Oncetheconditionbecomesfalse,theloopstopsrepeating.

Windows:ApopularoperatingsystemdevelopedbytheMicrosoftCorporationandusedinhomesandofficesaroundtheworldforstoring,processinganddisplayingcontenttoitsusers.

Page 131: Programming a Primer Coding Fo

Indexabstraction,5–7,39,42,43,47,61,82,132

address,17

agent

trading,6

Ajax,131

algorithm,121

ShortestPath,125

Sorting,123

application

mobile,17

arguments,39

ArtificialIntelligence,126

Assembly,7

backslash,18

BigData,145

BigIdeas,143

bit,77

block,28

Boolean,25

Bootstrap,130

Break,35

bugs,11

byte,77

C++,139

career,4

children,59

class,53,56

client-side,8

CloudComputing,144

compiled,7

compiler,7

computer

instruction,4

computerscience,xiii,8,121,163,164

concatenation,21

conditions,25

constructor,54

consultant,4

continue,35

CSS,8,86

Page 132: Programming a Primer Coding Fo

3DPrinting,149

datatype,17

decrement,22

deployment,11

developer

web,4

development

web,71

dictionary,19

Django,131

dotnotation,52

EdsgerDjikstra,125

Facebook,4,93,106,134

float,18

forloop,31

fun,5

function,22,39

Google,61

GraphicalUserInterface(GUI),61

HelloWorld,16

high-level,47

HTML,6,8,84,103

HyperTextTransferProtocol(HTTP),83

GETrequest,83

Ifstatement,27,30

Implementation,10

increment,22

indentation,29

indie,4

inheritance,57

input,6,22

instance,53

integers,18

Internet,75

interpreted,7

interpreter,7

Intranet,75

IPaddress,76

IPv4,77

JavaScript,7,8,93,131

jQuery,131

key,19

Page 133: Programming a Primer Coding Fo

library,47

import,62

LinkedIn,4

list,18

LocalAreaNetworks,74

localhost,81

logicaloperator,26

Maintenance,11

MarkZuckerberg,xiii

Microsoft,4,9,61,62,84,121,135,140,145,149,164,168

mobileapplication,17

consultant,4

MVC,132

network,74

NewLearningStyles,148

Notepad++,9

No-TouchInterfaces,149

object,52

Objective-C,135

object-oriented,51

operatingsystem,5

operation,20,43

numerical,43

operator

equality,25

output,6,22

OxfordUniversity,122

packet,79

PageRank,122

parameter,39,47

PHP,102

planning,10

programming

instructions,6

language,7

procedural,52

programminglanguage

compiled,7

high-level,7

interpreted,7

low-level,7

Python,7,15,131

Page 134: Programming a Primer Coding Fo

dictionary,19

list,18

networking,76

operations,20

syntax,28

queryinglanguage,8

returnvalue,40

Ruby,7,8,102,130,134,136,137

RubyonRails,134

security,147

self-employed,4

server-side,8,81,101,102,110,117,130,137,167

ShortestPath,125

socket

bind,80

sorting,123

sourcecode,7

SQL,8,110

INSERT,112

PHP,115

SELECT,111

UPDATE,113

stockmarket,6

string,18

manipulation,20

placeholder,23

subclass,59

syntax,28

TCP,78

texteditor,9

TextWrangler,9

TheInternetofThings,146

top-down,43

tradingagent,6

UDP,78

variable,17

name,17

value,17

WearableTechnology,149

webdeveloper,4

Whileloop,34

WideAreaNetworks,74

Page 135: Programming a Primer Coding Fo

Windows8,5

wxPython,62

widget,63

wx.StatusBar,64