WeekOne:IntroductionASHORTINTRODUCTIONTOHARDWARE,SOFTWARE,ANDALGORITHMDEVELOPMENT
Outline• Inthischapteryouwilllearn:• Aboutcomputer hardware,softwareandprogramming• Howtowriteandexecute yourfirstPythonprogram• Howtodiagnose andfixprogramming errors• Howtousepseudocode todescribe analgorithm
4/6/16 2
OurFirstDefinitionAlgorithm:
• Analgorithm isastepbystepdescriptionofhowtosolveaproblem
4/6/16 3
ComputerPrograms• Acomputerprogramtellsacomputerthesequenceofstepsneededtocompleteaspecifictask• Theprogramconsists ofaverylargenumber ofprimitive (simple)instructions
• Computerscancarryoutawiderangeoftasksbecausetheycanexecutedifferentprograms• Eachprogramisdesigned todirect thecomputertoworkonaspecific task
Programming:
• Theactofdesigning,implementing,andtestingcomputerprograms
4/6/16 4
HardwareandSoftwareTHEBUILDINGBLOCKSTHATMAKEUPACOMPUTER
4/6/16 5
Hardware• Hardware consistsofthephysicalelementsinacomputersystem.• Someveryvisible examples arethemonitor, themouse,external storage,andthekeyboard.
• Thecentralprocessingunit(CPU)performsprogramcontrolanddataprocessing
• Storagedevicesincludememory(RAM)andsecondarystorage• Harddisk• Flashdrives• CD/DVDdrives
• Input/outputdevicesallowtheusertointeractwiththecomputer• Mouse, keyboard,printer,screen…
4/6/16 6
SimpleViewofaComputer’sComponents
4/6/16 7
TheCPU• TheCPUhastwocomponents,thecontrolunit andthearithmeticlogicunit
• Thecontrolunitdirectsoperationoftheprocessor.• Allcomputerresources aremanaged bythecontrolunit.• Itcontrolscommunication andco-ordination between input/output devices.• Itreadsandinterprets instructions anddetermines the sequence forprocessing thedata.
• Itprovidestiming andcontrolsignals
• Thearithmeticlogicunit containsthecircuitrytoperformcalculationsanddocomparisons.• Itistheworkhorseportionofthecomputer andits jobistodopreciselywhatthecontrolunittells it todo.
4/6/16 8
Storage• Therearetwotypesofstorage:• PrimaryStorage• SecondaryStorage
• Primarystorageiscomposedofmemorychips:electroniccircuitsthatcanstoredataaslongasitisprovidedelectricpower
• Secondarystorageprovidesaslower,lessexpensivestoragethatispersistent:thedatapersistswithoutelectricpower
• Computersstorebothdataandprograms• Thedataandprogramarelocated insecondary storageandloaded intomemorywhentheprogramisexecuted
4/6/16 9
Memory• Asimplewaytoenvisionprimarymemoryisatableofcellsallthesamesize,onebyte,andeachcontainingauniqueaddressbeginningwith0.• The“typical” computer hasamainmemoryrangingfrom4gigabytes (GB),to32GB.
• Howbigisagigabyte?• Abyteis8bits.• Akilobyte,KB,is1024bytes,or“about1thousand bytes.”• Amegabyte,MB,is1,048,576bytes,or“about1million bytes.”• Agigabyte,GB,is1,073,741,824bytesor“about1billion bytes.”
4/6/16 10
ExecutingaProgram• Programinstructionsanddata(suchastext,numbers,audio,orvideo)arestoredindigitalformat
• Whenaprogramisstarted,itisbroughtintomemory,wheretheCPUcanreadit.
• TheCPUrunstheprogramoneinstructionatatime.• Theprogrammayreacttouser input.
• Theinstructionsanduserinputguidetheprogramexecution• TheCPUreadsdata(including user input),modifies it,andwrites itbacktomemory,thescreen,orsecondary storage.
4/6/16 11
Software• Software istypicallyrealizedasanapplicationprogram• MicrosoftWordisanexample ofsoftware• ComputerGames aresoftware• Operatingsystems anddevicedriversarealsosoftware
• Software• Software isasequence ofinstructions anddecisions implemented insomelanguage andtranslated toaformthatcanbeexecuted orrunonthecomputer.
• Computersexecuteverybasicinstructionsinrapidsuccession• Thebasic instructions canbegroupedtogether toperformcomplex tasks
• Programmingistheactofdesigningandimplementingcomputerprograms
4/6/16 12
Introduction toAlgorithms• Ifyouwantacomputertoperformatask,youstartbywritinganalgorithm
• AnAlgorithm is:• asequence (theordermattering) ofactions totaketoaccomplish thegiventask
• Analgorithm is likearecipe; itisasetofinstructions written inasequencethatachieves agoal
• Forcomplexproblemssoftwaredeveloperswriteanalgorithmbeforetheyattempttowriteacomputerprogram
• ForthisclasswewillALWAYSwriteanalgorithmforeachproject
• Developingalgorithmsisafundamentalproblemsolvingskill• Ithasuses inmanyfields outside ofComputer Science
4/6/16 13
Algorithm:FormalDefinitionAnalgorithmdescribesasequenceofstepsthatis:
1. Unambiguousa. No “assumptions” arerequired toexecute thealgorithmb. Thealgorithm uses precise instructions
2. Executablea. Thealgorithm canbecarriedout inpractice
3. Terminatinga. Thealgorithmwilleventually cometoanend,orhalt
4/6/16 14
ProblemSolving:AlgorithmDesign• Algorithmsaresimplyplans• Detailed plansthatdescribe thestepstosolveaspecific problem
• Youalreadyknowquiteafew• Calculate theareaofacircle• Findthe length ofthehypotenuse ofatriangle
• Someproblemsaremorecomplexandrequiremoresteps• Calculate PIto100decimal places• Calculate thetrajectoryofamissile
4/6/16 15
ASimpleExample
4/6/16
• Asimplealgorithmtogetyourselfadrinkoforangejuice• Forsimplicity, thefollowingaretrue:• Youhaveacleanglass inthecabinet• Youhaveorange juiceinyourrefrigerator
• Soonevalidalgorithmis:1. getaglass fromyourcabinet2. gototherefrigeratorandgettheorangejuicecontainer3. opentheorange juicecontainer4. pourtheorange juicefromthecontainer intotheglass5. puttheorangejuicecontainer backintherefrigerator6. drinkyourjuice
16
SecondExample:SelectingaCarProblem Statement:
• You have the choice of buying two cars.
• One is more fuel efficient than the other, but also more expensive.
• You know the price and fuel efficiency (in miles per gallon, mpg) of both cars.
• You plan to keep the car for ten years.
• Which car is the better deal?
4/6/16 17
Developing theAlgorithmDeterminetheinputsandoutputs
Fromtheproblemstatementweknow:• Car1:Purchaseprice,FuelEfficiency• Car2:Purchaseprice,FuelEfficiency• Pricepergallon=$4.00• Annualmiles driven=15,000• Lengthoftime =10years
Foreachcarweneedtocalculate:• Annualfuelconsumed foreachcar• Annualfuelcostforeachcar• Operatingcostforeachcar• Total costofeachCar
• Thenweselectthecarwiththelowesttotalcost
4/6/16 18
Translating theAlgorithmtopseudocode• Breakdowntheproblemintosmallertasks• ‘Calculate totalcost’ foreach car• Tocalculate thetotalcostforeachyearweneed tocalculate theoperating cost• Theoperating costdepends ontheannual fuelcost• Theannualfuelcost isthepricepergallon*theannual fuelconsumed• Theannualfuelconsumed istheannualmiles drive/fuelefficiency
• Describeeachsubtaskaspseudocode• totalcost=purchase price+operating cost
4/6/16 19
ThePseudocodeForeachCar,computethetotalcost
Annualfuelconsumed =annualmiles driven/fuelefficiencyAnnualfuelcost=pricepergallon*annual fuelconsumedOperatingcost=Length oftime*annual fuelcostTotal cost=purchaseprice+operatingcost
Iftotalcost1<totalcost2Chose Car1
ElseChoose Car2
4/6/16 20
BankAccountExample• ProblemStatement:• Youput$10,000intoabankaccountthatearns 5percent interest peryear.Howmanyyearsdoes ittakefortheaccountbalance tobedouble theoriginal?
• Howwouldyousolveit?• Manualmethod• Makeatable• Addlinesuntildone
• Useaspreadsheet!• Writeaformula• Perline,basedonlineabove
4/6/16 21
Developthealgorithmsteps• Youput$10,000intoabankaccountthatearns 5percent interest peryear.Howmanyyearsdoes ittakefortheaccountbalance tobedouble theoriginal?
• Breakitintosteps• Startwithayearvalueof0andabalance of$10,000• Repeat thefollowingwhilethebalance is less than$20,000• Add1totheyearvalue• Multiply thebalance by1.05• (5%increase)
• Reportthefinalyearvalueastheanswer
4/6/16 22
Translate topseudocode• Pseudocode• Half-waybetween natural language andaprogramming language
• ModifiedSteps• Settheyearvalueof0• Setthebalance to$10,000• While thebalance is lessthan$20,000• Add1totheyearvalue• Multiply thebalance by1.05
• Reportthefinalyearvalueastheanswer
• ThepseudocodeiseasilytranslatedintoPython
4/6/16 23
ThePythonLanguage• Intheearly1990’s,GuidovanRossumdesignedwhatwouldbecomethePythonprogramminglanguage
• VanRossumwasdissatisfiedwiththelanguagesavailable• Theywereoptimized towrite largeprogramsthatexecuted quickly
• Heneededalanguagethatcouldnotonlybeusedtocreateprogramsquicklybutalsomakethemeasytomodify• Itwasdesigned tohaveamuchsimpler andcleaner syntaxthanotherpopular languages suchasJava,CandC++ (making iteasier tolearn)
• Python isinterpreted, making iteasier todevelop andtestshortprograms
• PythonprogramsareexecutedbythePythoninterpreter• The interpreter readsyourprogramandexecutes it
4/6/16 24
ProgrammingEnvironments• Thereareseveralwaysofcreatingacomputerprogram• UsinganIntegratedDevelopment Environment (IDE)• Usingatexteditor
• Youshouldusethemethodyouaremostcomfortablewith
• WewillbeusingIDLE inthiscourse
• TheTextbookusestheWingIDE
4/6/16 25
Organizeyourwork• Your‘sourcecode’ isstoredin.pyfiles
• Createafolderforthiscourse
• Createonefolderperprograminsidethecoursefolder• Aprogramcanconsist ofseveral .pyfiles
• BesureyouknowwhereyourIDEstoresyourfiles• Youneed tobeable tofindyoufiles
• Backupyourfiles:• ToaUSBflashdrive• Toanetworkdrive
4/6/16 26
Python interactivemode• Likeotherlanguagesyoucanwrite/saveacompletePythonprograminafileandlettheinterpreterexecutetheinstructionsallatonce.
• Alternativelyyoucanruninstructionsoneatatimeusinginteractivemode.• Itallowsquick‘testprograms’ tobewritten.• Interactivemodeallows youtowritepythonstatements directly intheconsolewindow
4/6/16 27
SourceCodetoaRunningProgram• Thecompilerreadsyourprogramandgeneratesbytecodeinstructions(simpleinstructionsforthePythonVirtualmachine)• ThePythonVirtualmachine isaprogramthat issimilar totheCPUofyourcomputer
• Anynecessary libraries (e.g.fordrawinggraphics)areautomatically locatedandincluded bythevirtualmachine
4/6/16 28
BasicPythonSyntax:Print• UsingthePython‘print()’ function.• Afunction isacollection ofprogramming instructions thatcarryoutaparticular task(inthiscasetoprintavalueonscreen).
• It’scodethatsomebody elsewroteforyou!
4/6/16 29
Syntax forPythonFunctions• Touse,orcall,afunctioninPythonyouneedtospecify:• Thenameofthefunction thatyouwanttouse(inthepreviousexample thenamewasprint)
• Anyvalues (arguments) needed bythefunction tocarryoutitstask(inthiscase,“HelloWorld!”).
• Arguments areenclosed inparentheses andmultiple arguments areseparatedwithcommas.
• Asequence ofcharactersenclosed inquotations marksarecalled astring
4/6/16 30
MoreExamplesoftheprintFunction• Printingnumericalvalues• print(3 +4)• Evaluatestheexpression 3+4anddisplays7
• Passingmultiplevaluestothefunction• print(“the answer is”,6*7)• DisplaysTheansweris42• Eachvaluepassed tothefunction isdisplayed, oneafteranother, withablank
spaceaftereachvalue
• Bydefaulttheprintfunctionstartsanewlineafteritsargumentsareprinted• print(“Hello”)• print(“World!”)• Prints twolinesoftext• Hello• World!
4/6/16 31
Errors• TherearetwoCategoriesofErrors:• Compile-timeErrors• akaSyntaxErrors• Spelling,capitalization,punctuation• Orderingofstatements,matchingofparenthesis,quotes…
• Noexecutableprogramiscreatedbythecompiler• Correctfirsterrorlisted,thencompileagain.• Repeatuntilallerrorsarefixed
• Run-timeErrors• akaLogicErrors• Theprogramruns,butproducesunintendedresults• Theprogrammay‘crash’
4/6/16 32
SyntaxErrors• Syntaxerrorarecaughtbythecompiler
• Whathappensifyou• Miss-capitalize aword: Print("HelloWorld!")• Leaveoutquotes print(Hello World!)• Mismatch quotes print("Hello World!')• Don’tmatchbrackets print('Hello'
• TypeeachexampleaboveintheWingPythonShellwindow• Whaterrormessages aregenerated?
4/6/16 33
LogicErrors• Whathappensifyou• Dividebyzero print(1/0)• Misspell output print("Hello,Word!")• Forgettooutput Remove line2
• Programswillcompileandrun• Theoutputmaynotbeasexpected
• TypeeachexampleaboveinthePythonShellwindow• Whaterrormessages aregenerated?
4/6/16 34
Summary:ComputerBasics• Computersrapidlyexecuteverysimpleinstructions
• AProgram isasequenceofinstructionsanddecisions
• Programming istheart(andscience)ofdesigning,implementing,andtestingcomputerprograms
• TheCentralProcessingUnit(CPU)performsprogramcontrolanddataprocessing
• Storagedevicesincludememoryandsecondarystorage(e.g.,aUSBFlashDrive)
4/6/16 35
Summary: Python• PythonwasdesignedinawaythatmakesiteasiertolearnthanotherprogramminglanguagessuchasJava,CandC++.
• ThedesignersgoalwastogivePythonsimplerandcleanersyntax.
• Setasidesometimetobecomefamiliarwiththeprogrammingenvironmentthatyouwilluseforyourclasswork.• Itisimportant topracticewiththetoolsoyoucanfocuson learning Python
• Aneditorisaprogramforenteringandmodifyingtext,suchasaPythonprogram.
4/6/16 36
Summary: Python• Pythoniscasesensitive.• Youmustbecarefulaboutdistinguishing between upperandlowercaseletters.
• ThePythoncompilertranslatessourcecodeintobytecodeinstructionsthatareexecutedbytheVirtualmachine.
• Afunctioniscalledbyspecifyingthefunction’snameanditsparameters.
• Astringisasequenceofcharactersenclosedinquotationmarks.
4/6/16 37
Summary: Errorsandpseudocode• Acompile-timeerrorisaviolationoftheprogramminglanguagerulesthatisdetectedbythecompiler.
• Arun-timeerrorcausesaprogramtotakeanactionthattheprogrammerdidnotintend.
• Pseudocodeisaninformaldescriptionofasequenceofstepsforsolvingaproblem.
• Analgorithmforsolvingaproblemisasequenceofstepsthatisunambiguous,executable,andterminating.
4/6/16 38