Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576...

of 38 /38
Week One: Introduction A SHORT INTRODUCTION TO HARDWARE, SOFTWARE, AND ALGORITHM DEVELOPMENT

Transcript of Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576...

Page 1: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

WeekOne:IntroductionASHORTINTRODUCTIONTOHARDWARE,SOFTWARE,ANDALGORITHMDEVELOPMENT

Page 2: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Outline• Inthischapteryouwilllearn:• Aboutcomputer hardware,softwareandprogramming• Howtowriteandexecute yourfirstPythonprogram• Howtodiagnose andfixprogramming errors• Howtousepseudocode todescribe analgorithm

4/6/16 2

Page 3: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

OurFirstDefinitionAlgorithm:

• Analgorithm isastepbystepdescriptionofhowtosolveaproblem

4/6/16 3

Page 4: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

ComputerPrograms• Acomputerprogramtellsacomputerthesequenceofstepsneededtocompleteaspecifictask• Theprogramconsists ofaverylargenumber ofprimitive (simple)instructions

• Computerscancarryoutawiderangeoftasksbecausetheycanexecutedifferentprograms• Eachprogramisdesigned todirect thecomputertoworkonaspecific task

Programming:

• Theactofdesigning,implementing,andtestingcomputerprograms

4/6/16 4

Page 5: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

HardwareandSoftwareTHEBUILDINGBLOCKSTHATMAKEUPACOMPUTER

4/6/16 5

Page 6: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 7: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

SimpleViewofaComputer’sComponents

4/6/16 7

Page 8: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 9: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Storage• Therearetwotypesofstorage:• PrimaryStorage• SecondaryStorage

• Primarystorageiscomposedofmemorychips:electroniccircuitsthatcanstoredataaslongasitisprovidedelectricpower

• Secondarystorageprovidesaslower,lessexpensivestoragethatispersistent:thedatapersistswithoutelectricpower

• Computersstorebothdataandprograms• Thedataandprogramarelocated insecondary storageandloaded intomemorywhentheprogramisexecuted

4/6/16 9

Page 10: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 11: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 12: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 13: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 14: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 15: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

ProblemSolving:AlgorithmDesign• Algorithmsaresimplyplans• Detailed plansthatdescribe thestepstosolveaspecific problem

• Youalreadyknowquiteafew• Calculate theareaofacircle• Findthe length ofthehypotenuse ofatriangle

• Someproblemsaremorecomplexandrequiremoresteps• Calculate PIto100decimal places• Calculate thetrajectoryofamissile

4/6/16 15

Page 16: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 17: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 18: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 19: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 20: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 21: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

BankAccountExample• ProblemStatement:• Youput$10,000intoabankaccountthatearns 5percent interest peryear.Howmanyyearsdoes ittakefortheaccountbalance tobedouble theoriginal?

• Howwouldyousolveit?• Manualmethod• Makeatable• Addlinesuntildone

• Useaspreadsheet!• Writeaformula• Perline,basedonlineabove

4/6/16 21

Page 22: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 23: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 24: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 25: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

ProgrammingEnvironments• Thereareseveralwaysofcreatingacomputerprogram• UsinganIntegratedDevelopment Environment (IDE)• Usingatexteditor

• Youshouldusethemethodyouaremostcomfortablewith

• WewillbeusingIDLE inthiscourse

• TheTextbookusestheWingIDE

4/6/16 25

Page 26: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Organizeyourwork• Your‘sourcecode’ isstoredin.pyfiles

• Createafolderforthiscourse

• Createonefolderperprograminsidethecoursefolder• Aprogramcanconsist ofseveral .pyfiles

• BesureyouknowwhereyourIDEstoresyourfiles• Youneed tobeable tofindyoufiles

• Backupyourfiles:• ToaUSBflashdrive• Toanetworkdrive

4/6/16 26

Page 27: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Python interactivemode• Likeotherlanguagesyoucanwrite/saveacompletePythonprograminafileandlettheinterpreterexecutetheinstructionsallatonce.

• Alternativelyyoucanruninstructionsoneatatimeusinginteractivemode.• Itallowsquick‘testprograms’ tobewritten.• Interactivemodeallows youtowritepythonstatements directly intheconsolewindow

4/6/16 27

Page 28: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

SourceCodetoaRunningProgram• Thecompilerreadsyourprogramandgeneratesbytecodeinstructions(simpleinstructionsforthePythonVirtualmachine)• ThePythonVirtualmachine isaprogramthat issimilar totheCPUofyourcomputer

• Anynecessary libraries (e.g.fordrawinggraphics)areautomatically locatedandincluded bythevirtualmachine

4/6/16 28

Page 29: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

BasicPythonSyntax:Print• UsingthePython‘print()’ function.• Afunction isacollection ofprogramming instructions thatcarryoutaparticular task(inthiscasetoprintavalueonscreen).

• It’scodethatsomebody elsewroteforyou!

4/6/16 29

Page 30: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 31: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 32: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 33: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

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

Page 34: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

LogicErrors• Whathappensifyou• Dividebyzero print(1/0)• Misspell output print("Hello,Word!")• Forgettooutput Remove line2

• Programswillcompileandrun• Theoutputmaynotbeasexpected

• TypeeachexampleaboveinthePythonShellwindow• Whaterrormessages aregenerated?

4/6/16 34

Page 35: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Summary:ComputerBasics• Computersrapidlyexecuteverysimpleinstructions

• AProgram isasequenceofinstructionsanddecisions

• Programming istheart(andscience)ofdesigning,implementing,andtestingcomputerprograms

• TheCentralProcessingUnit(CPU)performsprogramcontrolanddataprocessing

• Storagedevicesincludememoryandsecondarystorage(e.g.,aUSBFlashDrive)

4/6/16 35

Page 36: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Summary: Python• PythonwasdesignedinawaythatmakesiteasiertolearnthanotherprogramminglanguagessuchasJava,CandC++.

• ThedesignersgoalwastogivePythonsimplerandcleanersyntax.

• Setasidesometimetobecomefamiliarwiththeprogrammingenvironmentthatyouwilluseforyourclasswork.• Itisimportant topracticewiththetoolsoyoucanfocuson learning Python

• Aneditorisaprogramforenteringandmodifyingtext,suchasaPythonprogram.

4/6/16 36

Page 37: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Summary: Python• Pythoniscasesensitive.• Youmustbecarefulaboutdistinguishing between upperandlowercaseletters.

• ThePythoncompilertranslatessourcecodeintobytecodeinstructionsthatareexecutedbytheVirtualmachine.

• Afunctioniscalledbyspecifyingthefunction’snameanditsparameters.

• Astringisasequenceofcharactersenclosedinquotationmarks.

4/6/16 37

Page 38: Week One: Introductionkoclab.cs.ucsb.edu/teaching/cs8/docx/ch01.pdf• A megabyte, MB, is 1,048,576 bytes, or “about 1 million bytes.” ... • Python programs are executed by the

Summary: Errorsandpseudocode• Acompile-timeerrorisaviolationoftheprogramminglanguagerulesthatisdetectedbythecompiler.

• Arun-timeerrorcausesaprogramtotakeanactionthattheprogrammerdidnotintend.

• Pseudocodeisaninformaldescriptionofasequenceofstepsforsolvingaproblem.

• Analgorithmforsolvingaproblemisasequenceofstepsthatisunambiguous,executable,andterminating.

4/6/16 38