Python Programming: An Introduction to Computer Science

(Nora) #1
2.3.ELEMENTSOFPROGRAMS 15

What is the Celsiustemperature? 100
The temperature is 212.0degrees fahrenheit.


YoucanseethatSuzieusedthevaluesof0 and 100 totestherprogram. It looksprettygood,andsheis
satisfiedwithhersolution.Apparently, nodebuggingis necessary.


2.3 ElementsofPrograms.


Now thatyouknow somethingabouttheprogrammingprocess,youarealmostreadyto startwritingprograms
onyourown.Beforedoingthat,though,youneeda morecompletegroundingin thefundamentalsofPython.
Thenextfewsectionswilldiscusstechnicaldetailsthatareessentialtowritingcorrectprograms. This
materialcanseema bittedious,but youwillhave to masterthesebasicsbeforeplungingintomoreinteresting
waters.


2.3.1 Names


Youhave alreadyseenthatnamesareanimportantpartofprogramming.We give namestomodules(e.g.,
convert) andto thefunctionswithinmodules(e.g.,main). Variablesareusedto give namesto values(e.g.,
celsiusandfahrenheit).Technically, allthesenamesarecalledidentifiers. Pythonhassomerules
abouthow identifiersareformed.Everyidentifiermustbeginwitha letterorunderscore(the“” character)
whichmaybefollowedbyany sequenceofletters,digits,orunderscores.Thisimpliesthata singleidentifier
cannotcontainany spaces.
Accordingtotheserules,allofthefollowingarelegalnamesinPython:


x
celsius
spam
spam2
SpamAndEggs
Spam_and_Eggs


Identifiersarecase-sensitive, sospam,Spam,sPam, andSPAMarealldifferentnamestoPython.Forthe
mostpart,programmersarefreeto chooseany namethatconformstotheserules.Goodprogrammersalways
trytochoosenamesthatdescribethethingbeingnamed.
Oneotherimportantthingtobeawareofis thatsomeidentifiersarepartofPythonitself.Thesenames
arecalledreservedwordsandcannotbeusedasordinaryidentifiers.ThecompletelistofPythonreserved
wordsis showninTable2.1.


and del for is raise
assert elif from lambda return
break else global not try
class except if or while
continue exec import pass yield
def finally in print

Table2.1:PythonReservedWords.

2.3.2 Expressions.


Programsmanipulatedata. Thefragmentsofcodethatproduceorcalculatenewdatavaluesarecalled
expressions. Sofarourprogramexampleshave dealtmostlywithnumbers,soI’ll usenumericdatato
illustrateexpressions.

Free download pdf