Chapter 2: Data and Expressions
Withthischapter,webeginadetaileddiscussionoftheconceptsandtechniquesof
computerprogramming.Westartbylookingatissuesrelatedtotherepresentation,
manipulation,andinput/outputofdata—fundamentaltoallcomputing.
1Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons
Thegeneration,collection,andanalysisofdataisadrivingforceintoday’s
world.Thesheeramountofdatabeingcreatedisstaggering.
Chainstoresgenerateterabytesofcustomerinformation,lookingforshopping
patternsofindividuals.Facebookusershavecreated40billionphotosrequiring
morethanapetabyteofstorage.Acertainradiotelescopeisexpectedto
generateanexabyteofinformationeveryfourhours.Alltold,thecurrent
amountofdatacreatedeachyearisestimatedtobealmosttwozettabytes,
morethandoublingeverytwoyears.
Inthischapter,welookathowdataisrepresentedandoperatedoninPython.
2Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons
Motivation
3Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons
Totakesomethingliterallyistotakeitat“facevalue.”Thesameistrue
ofliteralsinprogramming.Aliteralisasequenceofoneofmore
charactersthatstandsforitself,suchastheliteral12.Welookat
numericliteralsinPython.
4Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Literals
Numeric Literals
Anumericliteralisaliteralcontainingonlythedigits0–9,anoptional
signcharacter(+or-),andapossibledecimalpoint.(Thelettereis
alsousedinexponentialnotation,shownnext).
Ifanumericliteralcontainsadecimalpoint,thenitdenotesa
floating-pointvalue,or“float”(e.g.,10.24);otherwise,itdenotesan
integervalue(e.g.,10).
Commasareneverusedinnumericliterals.
5Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
6Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Example Numerical Values
Sincenumericliteralswithoutaprovidedsigncharacterdenotepositivevalues,
anexplicitpositivesignisrarelyused.
Let’s Try It
7
WhichofthefollowingarevalidnumericliteralsinPython?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
8
Limits of Range in Floating-Point Representation
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
ThereisnolimittothesizeofanintegerthatcanberepresentedinPython.
Floatingpointvalues,however,havebothalimitedrangeandalimited
precision.
Pythonusesadouble-precisionstandardformat(IEEE754)providinga
rangeof10
-308
to10
308
with16to17digitsofprecision.Todenotesucha
rangeofvalues,floating-pointscanberepresentedinscientificnotation.
9
Itisimportanttounderstandthelimitationsoffloating-point
representation.Forexample,themultiplicationoftwovaluesmayresultin
arithmeticoverflow,aconditionthatoccurswhenacalculatedresultistoo
largeinmagnitude(size)toberepresented,
>>>1.5e200*2.0e210
inf
Thisresultsinthespecialvalueinf(“infinity”)ratherthanthe
arithmeticallycorrectresult3.0e410,indicatingthatarithmeticoverflowhas
occurred.
Similarly,thedivisionoftwonumbersmayresultinarithmeticunderflow,a
conditionthatoccurswhenacalculatedresultistoosmallinmagnitudeto
berepresented,
>>>1.0e-300/1.0e100
0.0
Thisresultsin0.0ratherthanthearithmeticallycorrectresult1.0e-400,
indicatingthatarithmeticunderflowhasoccurred.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Let’s Try It
10
Whatdoeachofthefollowingarithmeticexpressions
evaluateto?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
11
Limits of Precision in Floating-Point Representation
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Arithmeticoverflowandarithmeticunderflowareeasilydetected.Thelossof
precisionthatcanresultinacalculatedresult,however,isamuchmoresubtleissue.
Forexample,1/3isequaltotheinfinitelyrepeatingdecimal.33333333...,whichalso
hasrepeatingdigitsinbasetwo,.010101010....Sinceanyfloating-point
representationnecessarilycontainsonlyafinitenumberofdigits,whatisstoredfor
manyfloating-pointvaluesisonlyanapproximationofthetruevalue,ascanbe
demonstratedinPython,
>>>1/3
.3333333333333333
Here,therepeatingdecimalendsafterthe16thdigit.Consideralsothefollowing,
>>>3*(1/3)
1.0
Giventhevalueof1/3aboveas.3333333333333333,wewouldexpecttheresultto
be.9999999999999999,sowhatishappeninghere?
12Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
TheansweristhatPythondisplaysaroundedresulttokeepthenumberofdigits
displayedmanageable.However,therepresentationof1/3as.3333333333333333
remainsthesame,asdemonstratedbythefollowing,
>>>1/3+1/3+1/3+1/3+1/31+1/3
1.9999999999999998
Inthiscasewegetaresultthatreflectstherepresentationof1/3asanapproximation,
sincethelastdigitis8,andnot9.However,ifweusemultiplicationinstead,weagain
gettheroundedvaluedisplayed,
>>>6*(1/3)
2.0
Thebottomline,therefore,isthatnomatterhowPythonchoosestodisplay
calculatedresults,thevaluestoredislimitedinboththerangeofnumbersthatcan
berepresentedandthedegreeofprecision.Formosteverydayapplications,this
slightlossinaccuracyisofnopracticalconcern.However,inscientificcomputingand
otherapplicationsinwhichprecisecalculationsarerequired,thisissomethingthat
theprogrammermustbekeenlyawareof.
Let’s Try It
13
Whatdoeachofthefollowingarithmeticexpressions
evaluateto?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
14
Built-in Format Function
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Becausefloating-pointvaluesmaycontainanarbitrarynumberofdecimalplaces,the
built-informatfunctioncanbeusedtoproduceanumericstringversionofthevalue
containingaspecificnumberofdecimalplaces,
>>>12/5 >>>5/7
2.4 0.7142857142857143
>>>format(12/5,'.2f')>>>format(5/7,'.2f')
'2.40' '0.71'
Intheseexamples,formatspecifier'.2f'roundstheresulttotwodecimalplacesof
accuracyinthestringproduced.
For very large (or very small) values 'e' can be used as a format specifier.
>>> format(2 ** 100, '.6e')
'1.267651e+30'
Here,thevalueisformattedinscientificnotation,withsixdecimalplacesofprecision.
15Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Formattednumericstringvaluesareusefulwhendisplayingresultsinwhich
onlyacertainnumberofdecimalplacesneedtobedisplayed:
Withoutuseofformatspecifier:
>>>tax=0.08
>>>print('Yourcost:$',(1+tax)*12.99)
Yourcost:$14.029200000000001
Withuseofformatspecifier:
>>> print('Your cost: $', format((1 + tax) * 12.99, '.2f'))
Yourcost:$14.03
Finally,acommaintheformatspecifieraddscommaseparatorstotheresult.
>>>format(13402.25,',.2f')
13,402.24
Let’s Try It
16
Whatdoeachofthefollowingusesoftheformatfunction
produce?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
String Literals
Stringliterals,or“strings,”representasequenceofcharacters.
'Hello' 'Smith, John' "Baltimore, Maryland 21210"
InPython,stringliteralsmaybedelimited(surrounded)byamatching
pairofeithersingle(')ordouble(")quotes.Stringsmustbecontained
allononeline(exceptwhendelimitedbytriplequotes,discussedlater).
WehavealreadyseentheuseofstringsinChapter1fordisplaying
screenoutput,
>>>print('WelcometoPython!')
WelcometoPython!
17Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Astringmaycontainzeroormorecharacters,includingletters,digits,
specialcharacters,andblanks.Astringconsistingofonlyapairof
matchingquotes(withnothinginbetween)iscalledtheemptystring,
whichisdifferentfromastringcontainingonlyblankcharacters.Both
blankstringsandtheemptystringhavetheiruses,aswewillsee.
Stringsmayalsocontainquotecharactersaslongasdifferentquotes
(singlevs.double)areusedtodelimitthestring.
18Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Let’s Try It
19
Whatwillbedisplayedbyeachofthefollowing?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
The Representation of Character Values
Thereneedstobeawaytoencode(represent)characterswithina
computer.Althoughvariousencodingschemeshavebeendeveloped,
theUnicodeencodingschemeisintendedtobeauniversalencoding
scheme.
Unicodeisactuallyacollectionofdifferentencodingschemesutilizing
between8and32bitsforeachcharacter.Thedefaultencodingin
PythonusesUTF-8,an8-bitencodingcompatiblewithASCII,anolder,
stillwidelyusedencodingscheme.
Currently,thereareover100,000Unicode-definedcharactersformany
ofthelanguagesaroundtheworld.Unicodeiscapableofdefiningmore
thanfourbillioncharacters.Thus,alltheworld’slanguages,bothpast
andpresent,canpotentiallybeencodedwithinUnicode.
20Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Partial listing of the ASCII-compatible UTF-8 encoding scheme
21Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
UTF-8encodescharactersthathaveanorderingwithsequential
numericalvalues.Forexample,'A'isencodedas01000001(65),'B'is
encodedas01000010(66),andsoon.Thisisalsotruefordigit
characters,‘0’isencodedas48,‘1’as49,etc.
22Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Notethedifferencebetweenanumericrepresentation(thatcanbeused
inarithmeticcalculations)vs.anumberrepresentedasastringofdigit
characters(notusedincalculations).
Here,thebinaryrepresentationof124isthebinarynumberforthat
value.Thestringrepresentation‘124’consistsofalongersequenceof
bits,eightbits(onebyte)foreachdigitcharacter.
Pythonhasameansofconvertingbetweenacharacteranditsencoding.
TheordfunctiongivestheUTF-8(ASCII)encodingofagivencharacter.
Forexample,
ord('A')is65
Thechrfunctiongivesthecharacterforagivenencodingvalue,thus
chr(65)is'A'
Whileingeneralthereisnoneedtoknowthespecificencodingofa
givencharacter,therearetimeswhensuchknowledgecanbeuseful.
23Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Converting Between a Character and Its Encoding
Let’s Try It
24
Whatistheresultofeachofthefollowingconversions?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Controlcharactersarespecialcharactersthatarenotdisplayed,but
rathercontrolthedisplayofoutput,amongotherthings.Control
charactersdonothaveacorrespondingkeyboardcharacter,andthusare
representedbyacombinationofcharacterscalledanescapesequence.
Escapesequencesbeginwithanescapecharacterthatcausesthe
charactersfollowingitto“escape”theirnormalmeaning.Thebackslash
(\)servesastheescapecharacterinPython.Forexample,'\n',
representsthenewlinecontrolcharacter,thatbeginsanewscreenline,
print('Hello\nJenniferSmith')
whichisdisplayedasfollows:
Hello
JenniferSmith
25Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Control Characters
Let’s Try It
26
Whatisdisplayedbyeachofthefollowing?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Built-infunctionformatcanbeusedforcontrollinghowstringsare
displayed,inadditiontocontrollingthedisplayofnumericalvalues,
format(value,format_specifier)
wherevalueisthevaluetobedisplayed,andformat_specifiercan
containacombinationofformattingoptions.
27Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
String Formatting
Forexample,thefollowingproducesthestring'Hello'left-justifiedina
fieldwidthof20characters,
format('Hello', '<20')➝'Hello '
Toright-justifythestring,thefollowingwouldbeused,
format('Hello', '>20')➝' Hello'
Formattedstringsareleft-justifiedbydefault.Therefore,thefollowing
producethesameresult,
format('Hello', '<20')➝'Hello '
format('Hello', '20')➝ 'Hello '
28Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Tocenterastringthe'^'characterisused:
format('Hello', '^20')
Anotheruseoftheformatfunctionistocreateastringofblank
characters,whichissometimesuseful,
format('','15')➝' '
Finallyblanks,bydefault,arethefillcharacterforformattedstrings.
However,aspecificfillcharactercanbespecifiedasshownbelow,
>>>print('Hello', format('.','.<30'),'HaveaNiceDay!')
Hello.............................. HaveaNiceDay!
Here,asingleperiodisthecharacterprintedwithinafieldwidthof30,
thereforeultimatelyprintingout30periods.
29Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Let’s Try It
30
Whatisdisplayedbyeachofthefollowing?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
SometimesaprogramlinemaybetoolongtofitinthePython-
recommendedmaximumlengthof79characters.Therearetwowaysin
Pythontodealwithsuchsituations:
•implicitlinejoining
•explicitlinejoining
31Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Implicit and Explicit Line Joining
Therearecertaindelimitingcharactersthatallowalogicalprogramlinetospan
morethanonephysicalline.Thisincludesmatchingparentheses,squarebrackets,
curlybraces,andtriplequotes.
Forexample,thefollowingtwoprogramlinesaretreatedasonelogicalline:
print('Name:',student_name, 'Address:', student_address,
'Number of Credits:', total_credits, 'GPA:', current_gpa)
Matchingquotes(exceptfortriplequotes)mustbeonthesamephysicalline.For
example,thefollowingwillgenerateanerror:
print('This program will calculate a restaurant tab for a couple
with a gift certificate, and a restaurant tax of 3% ')
32Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Implicit Line Joining
open quote
close quote
Inadditiontoimplicitlinejoining,programlinesmaybeexplicitlyjoined
byuseofthebackslash(\)character.Programlinesthatendwitha
backslashthatarenotpartofaliteralstring(thatis,withinquotes)continue
onthefollowingline.
numsecs_1900_dob=((year_birth21900)*avg_numsecs_year)+\
((month_birth21)*avg_numsecs_month)+\
(day_birth*numsecs_day)
33Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Explicit Line Joining
Itisalongtraditionincomputersciencetodemonstrateaprogramthat
simplydisplays“HelloWorld!”asanexampleofthesimplestprogram
possibleinaparticularprogramminglanguage.InPython,thecomplete
HelloWorldprogramiscomprisedofoneprogramline:
print('HelloWorld!')
WetakeatwistonthistraditionandgiveaPythonprogramthatdisplaysthe
Unicodeencodingforeachofthecharactersinthestring“HelloWorld!”
instead.Thisprogramutilizesthefollowingprogrammingfeatures:
➤stringliterals➤print ➤ordfunction
34Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Hello World Unicode Encoding
Let’s Apply It
35Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Thestatementsonlines1,3,and6arecommentstatements.Theprint
functiononline4displaysthemessage‘HelloWorld!’.Doublequotesareused
todelimitthecorrespondingstring,sincethesinglequoteswithinitaretobe
takenliterally.Theuseofprintonline7printsouttheUnicodeencoding,one-
by-one,foreachofthecharactersinthe“HelloWorld!”string.Notefromthe
programexecutionthatthereisaUnicodeencodingfortheblankcharacter
(32),aswellastheexclamationmark(33).
36Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
37Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
38Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
39Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
40Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
41Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
42Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
43Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.1 Literals
Sofar,wehaveonlylookedatliteralvaluesinprograms.However,the
trueusefulnessofacomputerprogramistheabilitytooperateon
differentvalueseachtimetheprogramisexecuted.Thisisprovidedby
thenotionofavariable.Welookatvariablesandidentifiersnext.
44Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Variables and Identifiers
What Is a Variable?
Avariableisaname(identifier)thatisassociatedwithavalue,
45Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Avariablecanbeassigneddifferentvaluesduringaprogram’s
execution—hence,thename“variable.”
Whereveravariableappearsinaprogram(exceptontheleft-handside
ofanassignmentstatement),itisthevalueassociatedwiththevariable
thatisused,andnotthevariable’sname,
46Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Variablesareassignedvaluesbyuseoftheassignmentoperator,=,
Assignmentstatementsoftenlookwrongtonoviceprogrammers.
Mathematically,num=num+1doesnotmakesense.Incomputing,
however,itisusedtoincrementthevalueofagivenvariablebyone.Itis
moreappropriate,therefore,tothinkofthe=symbolasanarrow
symbol
47Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Whenthoughtofthisway,itmakesclearthattherightsideofan
assignmentisevaluatedfirst,thentheresultisassignedtothe
variableontheleft.Anarrowsymbolisnotusedsimplybecausethere
isnosuchcharacteronastandardcomputerkeyboard.
Variablesmayalsobeassignedtothevalueofanothervariable,
48Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Variables numand kare both associated with the same literal value 10 in
memory. One way to see this is by use of built-in function id,
Theidfunctionproducesauniquenumberidentifyingaspecificvalue
(object)inmemory.Sincevariablesaremeanttobedistinct,itwould
appearthatthissharingofvalueswouldcauseproblems.
Ifthevalueofnumchanged,wouldvariablekchangealongwithit?
49Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Thiscannothappeninthiscasebecausethevariablesrefertointeger
values,andintegervaluesareimmutable.Animmutablevalueisavalue
thatcannotbechanged.Thus,bothwillcontinuetorefertothesame
valueuntilone(orboth)ofthemisreassigned,
Ifnoothervariablereferencesthememorylocationoftheoriginalvalue,
thememorylocationisdeallocated(thatis,itismadeavailableforreuse).
Finally,inPythonthesamevariablecanbeassociatedwithvaluesof
differenttypeduringprogramexecution,
50Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
(Theabilityofavariabletobeassignedvaluesofdifferenttypeisreferred
toasdynamictyping,introducedlaterinthediscussionsofdatatypes.)
Let’s Try It
51
Whatdoeachofthefollowingevaluateto?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Variable Assignment and Keyboard Input
Thevaluethatisassignedtoagivenvariabledoesnothavetobe
specifiedintheprogram.Thevaluecancomefromtheuserbyuseofthe
inputfunctionintroducedinChapter1,
>>>name=input('Whatisyourfirstname?')
Whatisyourfirstname?John
Inthiscase,thevariablenameisassignedthestring'John'.Iftheuser
hitreturnwithoutenteringanyvalue,namewouldbeassignedtothe
emptystring('').
52Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Theinputfunctionreturnsastringtype.Forinputofnumericvalues,the
responsemustbeconvertedtotheappropriatetype.Pythonprovides
built-intypeconversionfunctionsint()andfloat()forthispurpose,
line=input('Howmanycreditsdoyouhave?')
num_credits=int(line)
line=input('Whatisyourgradepointaverage?')
gpa=float(line)
Theenterednumberofcredits,say'24',isconvertedtotheequivalent
integervalue,24,beforebeingassignedtovariablenum_credits.The
inputvalueofthegpa,say'3.2',isconvertedtotheequivalentfloating-
pointvalue,3.2.
Notethattheprogramlinesabovecouldbecombinedasfollows,
num_credits=int(input('Howmanycreditsdoyouhave?'))
gpa=float(input('What isyourgradepointaverage?'))
53Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Let’s Try It
54
Whatisdisplayedbyeachofthefollowing?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
What Is an Identifier?
Anidentifierisasequenceofoneormorecharactersusedtoprovidea
nameforagivenprogramelement.Variablenamesline,
num_credits,andgpaareeachidentifiers.
Pythoniscasesensitive,thus,Lineisdifferentfromline.Identifiers
maycontainlettersanddigits,butcannotbeginwithadigit.
Theunderscorecharacter,_,isalsoallowedtoaidinthereadabilityof
longidentifiernames.Itshouldnotbeusedasthefirstcharacter,
however,asidentifiersbeginningwithanunderscorehavespecial
meaninginPython.
55Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Spacesarenotallowedaspartofanidentifier.Thisisacommonerror
sincesomeoperatingsystemsallowspaceswithinfilenames.In
programminglanguages,however,spacesareusedtodelimit(separate)
distinctsyntacticentities.Thus,anyidentifiercontainingaspace
characterwouldbeconsideredtwoseparateidentifiers.
ExamplesofvalidandinvalididentifiersinPython
56Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Let’s Try It
57
Whatisdisplayedbyeachofthefollowing?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Keywords and Other
Predefined Identifiers in Python
Akeywordisanidentifierthathaspredefinedmeaninginaprogramming
language.Therefore,keywordscannotbeusedas“regular”identifiers.
Doingsowillresultinasyntaxerror,asdemonstratedintheattempted
assignmenttokeywordandbelow,
>>>and=10
SyntaxError:invalidsyntax
58Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
ThekeywordsinPythonarelistedbelow.
59Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
TodisplaythekeywordsinPython,typehelp()inthePythonshell,then
typekeywords(type'q'toquit).
60Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
61Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Thereareotherpredefinedidentifiersthatcanbeusedasregular
identifiers,butshouldnotbe.Thisincludesfloat,int,print,exit,and
quit,forexample.
Asimplewaytocheckwhetheraspecificidentifierisakeywordin
Pythonisasfollows
>>> 'exit' in dir(__builtins__)
True
>>> 'exit_program' in dir(__builtins__)
False
Let’s Try It
62
Whatisdisplayedbyeachofthefollowing?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Theprogrambelowcalculatesarestauranttabforacouplebasedontheuse
ofagiftcertificateandtheitemsordered.
Thisprogramutilizesthefollowingprogrammingfeatures:
➤variables
➤keyboardinput
➤built-informatfunction
➤typeconversionfunctions
63Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Restaurant Tab Calculation
Let’s Apply It
64Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Example Execution
65Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Example Program Execution
Line5providestherequired
initializationofvariables,with
variabletaxassignedto8%
(.08)usedinlines9,35,and
39.Tochangetherestaurant
tax,onlythislineofthe
programneedstobechanged.
Lines8–9displaywhatthe
programdoes.Lines30and31
totalthecostoftheordersfor
eachperson,assignedto
variablesamt_person1and
amt_person2.Lines34and
35computethetab,including
thetax(storedinvariable
tab).
Finally,lines38–41displaythe
costoftheordereditems,
followedbytheadded
restauranttaxandtheamount
dueafterdeductingthe
amountofthegiftcertificate.
66Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
67Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
68Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
69Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
70Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
71Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
72Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Anoperatorisasymbolthatrepresentsanoperationthatmaybe
performedononeormoreoperands.Forexample,the+symbol
representstheoperationofaddition.Anoperandisavaluethatagiven
operatorisappliedto,suchasoperands2and3intheexpression2+3.
Aunaryoperatoroperatesononlyoneoperand,suchasthenegation
operatorintheexpression-12.
Abinaryoperatoroperatesontwooperands,aswiththeaddition
operator.Mostoperatorsinprogramminglanguagesarebinary
operators.WelookatthearithmeticoperatorsinPythonnext.
73Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Operators
Arithmetic Operators
74Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
The+,-,*(multiplication)and/(division)arithmeticoperatorsperformtheusual
operations.Notethatthe-symbolisusedbothasaunaryoperator(fornegation)anda
binaryoperator(forsubtraction),
20-5➝15 (-asbinaryoperator)
-10*2➝-20 (-asunaryoperator)
Pythonalsoincludesanexponentiation(**)operator.
75Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Pythonprovidestwoformsofdivision.“True”divisionisdenotedbyasingle
slash,/.Thus,25/10evaluatesto2.5.Truncatingdivisionisdenotedbyadouble
slash,//,providingatruncatedresultbasedonthetypeofoperandsappliedto.
Whenbothoperandsareintegervalues,theresultisatruncatedintegerreferred
toasintegerdivision.Whenasleastoneoftheoperandsisafloattype,theresult
isatruncatedfloatingpoint.Thus,25//10evaluatesto2,while25.0//10
evaluatesto2.0.
76Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Asexampleuseofintegerdivision,thenumberofdozendoughnutsforvariable
numDoughnuts=29is:numDoughnuts//12➝29//12➝2
Lastly,themodulusoperator(%)givestheremainderofthedivisionofits
operands,resultinginacycleofvalues.
Themodulusandtruncating(integer)divisionoperatorsarecomplementsof
eachother.Forexample,29//12givesthenumberofdozendoughnuts,
while29%12givesthenumberofleftoverdoughnuts(5).
Let’s Try It
77
Whatdoeachofthefollowingarithmeticexpressions
evaluateto?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Thefollowingprogramcalculatestheapproximatenumberofatomsthatthe
averagepersoncontains,andthepercentageoftheuniversethatthey
comprise.
Thisprogramutilizesthefollowingprogrammingfeatures:
➤floating-pointscientificnotation
➤built-informatfunction
78Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Your Place in the Universe
Let’s Apply It
Neededvariablesnum_
atoms_universe,weight_
avg_person,andnum_
atoms_avg_personare
initializedinlines7–9.The
programgreetingisonline
12.
Line15inputstheperson’s
weight.Line18converts
theweighttokilogramsfor
thecalculationsonlines
21–22,whichcomputethe
desiredresults.
Finally,lines25–27display
theresults.
79Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
80Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
81Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
82Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
83Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
84Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
85Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
86Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Nowthatwehavelookedatarithmeticoperators,wewillseehow
operatorsandoperandscanbecombinedtoformexpressions.In
particular,wewilllookathowarithmeticexpressionsareevaluatedin
Python.Wealsointroducethenotionofadatatype.
87Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Expressions and Data Types
What Is an Expression?
88Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Anexpressionisacombinationofsymbolsthatevaluatestoavalue.Expressions,
mostcommonly,consistofacombinationofoperatorsandoperands,
4+(3*k)
Anexpressioncanalsoconsistofasingleliteralorvariable.Thus,4,3,andkare
eachexpressions.Thisexpressionhastwosubexpressions,4and(3*k).
Subexpression(3*k)itselfhastwosubexpressions,3andk.
Expressionsthatevaluatetoanumerictypearecalledarithmeticexpressions.A
subexpressionisanyexpressionthatispartofalargerexpression.Subexpressions
maybedenotedbytheuseofparentheses,asshownabove.Thus,forthe
expression4+(3*2),thetwooperandsoftheadditionoperatorare4and(3*2),
andthustheresultisequalto10.Iftheexpressionwereinsteadwrittenas
(4+3)*2,thenitwouldevaluateto14.
Let’s Try It
89
Whatdoeachofthefollowingarithmeticexpressions
evaluateto?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Operator Precedence
90Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Thewaywecommonlyrepresentexpressions,inwhichoperatorsappearbetween
theiroperands,isreferredtoasinfixnotation.Forexample,theexpression4+3is
ininfixnotationsincethe+operatorappearsbetweenitstwooperands,4and3.
Thereareotherwaysofrepresentingexpressionscalledprefixandpostfixnotation,
inwhichoperatorsareplacedbeforeandaftertheiroperands,respectively.
Theexpression4+(3*5)isalsoininfixnotation.Itcontainstwooperators,
+and*.Theparenthesesdenotethat(3*5)isasubexpression.Therefore,4and
(3*5)aretheoperandsoftheadditionoperator,andthustheoverallexpression
evaluatesto19.Whatiftheparentheseswereomitted,asgivenbelow?
4+3*5
Howwouldthisbeevaluated?Thesearetwopossibilities.
91Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
4+3*5➝4+15➝19 4+3*5➝7*5➝35
Somemightsaythatthefirstversionisthecorrectonebytheconventionsof
mathematics.However,eachprogramminglanguagehasitsownrulesforthe
orderthatoperatorsareapplied,calledoperatorprecedence,definedinan
operatorprecedencetable.Thismayormaynotbethesameasinmathematics,
althoughittypicallyis.
BelowistheoperatorprecedencetableforthePythonoperatorsdiscussedsofar.
92Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Inthetable,higher-priorityoperatorsareplacedabovelower-priorityones.Thus,
weseethatmultiplicationisperformedbeforeadditionwhennoparenthesesare
included,
4+3*5➝4+15➝19
Inourexample,therefore,iftheadditionistobeperformedfirst,parentheses
wouldbeneeded,
(4+3)*5➝7*5➝35
93Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Asanotherexample,considertheexpressionbelow.
4+2**5//10➝4+32//10➝4+3➝7
FollowingPython’srulesofoperatorprecedence,theexponentiationoperatoris
appliedfirst,thenthetruncatingdivisionoperator,andfinallytheaddition
operator.
Operatorprecedenceguaranteesaconsistentinterpretationofexpressions.
However,itisgoodprogrammingpracticetouseparenthesesevenwhennot
neededifitaddsclarityandenhancesreadability,withoutoverdoingit.Thus,the
previousexpressionwouldbebetterwrittenas,
4+(2**5)//10
Let’s Try It
94
Whatdoeachofthefollowingarithmeticexpressions
evaluatetousingoperatorprecedenceofPython?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Operator Associativity
95Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Aquestionthatyoumayhavealreadyhadis,“Whatiftwooperatorshavethe
samelevelofprecedence,whichoneisappliedfirst?”Foroperatorsfollowingthe
associativelaw(suchasaddition)theorderofevaluationdoesn’tmatter,
(2+3)+4➝92+(3+4)➝9
Inthiscase,wegetthesameresultsregardlessoftheorderthattheoperatorsare
applied.Divisionandsubtraction,however,donotfollowtheassociativelaw,
(a)(8-4)-2➝4-2➝28-(4-2)➝8-2➝6
(b)(8/4)/2➝2/2➝18/(4/2)➝8/2➝4
(c)2**(3**2)➝512 (2**3)**2➝64
Here,theorderofevaluationdoesmatter.
96Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Toresolvetheambiguity,eachoperatorhasaspecifiedoperatorassociativitythat
definestheorderthatitandotheroperatorswiththesamelevelofprecedence
areapplied.Alloperatorsgivenbelow,exceptforexponentiation,haveleft-to-
rightassociativity—exponentiationhasright-to-leftassociativity.
Let’s Try It
97
Whatdoeachofthefollowingarithmeticexpressions
evaluateto?
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Data Types
98Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Adatatypeisasetofvalues,andasetofoperatorsthatmaybeapplied
tothosevalues.Forexample,theintegerdatatypeconsistsofthesetof
integers,andoperatorsforaddition,subtraction,multiplication,and
division,amongothers.Integers,floats,andstringsarepartofasetof
predefineddatatypesinPythoncalledthebuilt-intypes.
Forexample,itdoesnotmakesensetotrytodivideastringbytwo,
'Hello'/2.Theprogrammerknowsthisbycommonsense.Pythonknows
itbecause'Hello'belongstothestringdatatype,whichdoesnotinclude
thedivisionoperation.
99Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Theneedfordatatypesresultsfromthefactthatthesameinternal
representationofdatacanbeinterpretedinvariousways,
Thesequenceofbitsinthefigurecanbeinterpretedasacharacter('A')oran
integer(65).Ifaprogramminglanguagedidnotkeeptrackoftheintendedtypeof
eachvalue,thentheprogrammerwouldhaveto.Thiswouldlikelyleadto
undetectedprogrammingerrors,andwouldprovideevenmoreworkforthe
programmer.Wediscussthisfurtherinthefollowingsection.
100Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Finally,therearetwoapproachestodatatypinginprogramminglanguages.In
statictyping,avariableisdeclaredasacertaintypebeforeitisused,andcan
onlybeassignedvaluesofthattype.
Indynamictyping,thedatatypeofavariabledependsonlyonthetypeofvalue
thatthevariableiscurrentlyholding.Thus,thesamevariablemaybeassigned
valuesofdifferenttypeduringtheexecutionofaprogram.
Pythonusesdynamictyping.
Mixed-Type Expressions
101Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Amixed-typeexpressionisanexpressioncontainingoperandsof
differenttype.TheCPUcanonlyperformoperationsonvalueswiththe
sameinternalrepresentationscheme,andthusonlyonoperandsofthe
sametype.Operandsofmixed-typeexpressionsthereforemustbe
convertedtoacommontype.Valuescanbeconvertedinoneoftwo
ways—byimplicit(automatic)conversion,calledcoercion,orbyexplicit
typeconversion.
102Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Coercionistheimplicit(automatic)conversionofoperandstoacommontype.
Coercionisautomaticallyperformedonmixed-typeexpressionsonlyifthe
operandscanbesafelyconverted,thatis,ifnolossofinformationwillresult.
Theconversionofinteger2tofloating-point2.0belowisasafeconversion—the
conversionof4.5tointeger4isnot,sincethedecimaldigitwouldbelost,
2+4.5➝2.0+4.5➝6.5safe(automaticconversionofinttofloat)
int float float float float
103Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Typeconversionistheexplicitconversionofoperandstoaspecifictype.Type
conversioncanbeappliedeveniflossofinformationresults.Pythonprovides
built-intypeconversionfunctionsint()andfloat(),withtheint()
functiontruncatingresults
2 + 4.5 ➝float(2) + 4.5 ➝2.0 + 4.5 ➝6.5 No loss of information
2 + 4.5 ➝2 + int(4.5) ➝2 + 4 ➝6 Loss of information
intfloat float float floatfloatfloat
intfloatint int intint int
104Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.3 Expressions and Data Types
Typeconversionfunctionsint()andfloat()
Notethatnumericstringscanalsobeconvertedtoanumerictype.Infact,we
havealreadybeendoingthiswhenusingintorfloatwiththeinput
function,
num_credits=int(input('Howmanycreditsdoyouhave?'))
ThefollowingPythonprogramrequestsfromtheuseratemperaturein
degreesFahrenheit,anddisplaystheequivalenttemperatureindegrees
Celsius.
Thisprogramutilizesthefollowingprogrammingfeatures:
➤arithmeticexpressions
➤operatorassociativity
➤built-informatfunction
105Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
Temperature Conversion Program
Let’s Apply It
Line10readstheFahrenheittemperatureentered,assignedtovariablefahren.Eitheranintegerora
floating-pointvaluemaybeentered,sincetheinputisconvertedtofloattype.Line13performsthe
calculationforconvertingFahrenheittoCelsius.Recallthatthedivisionandmultiplicationoperatorshave
thesamelevelofprecedence.Sincetheseoperatorsassociateleft-to-right,themultiplicationoperatoris
appliedfirst.Becauseoftheuseofthe“true”divisionoperator/,theresultoftheexpressionwillhave
floating-pointaccuracy.Finally,lines16–17outputtheconvertedtemperatureindegreesCelsius.
106Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
107Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
108Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
109Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
110Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
111Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
112Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
113Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.2 Variables and Identifiers
114
Welookattheproblemofcalculatingan
individual’sageinseconds.Itisnotfeasibleto
determineagivenperson’sagetotheexact
second.Thiswouldrequireknowing,tothe
second,whentheywereborn.Itwouldalso
involveknowingthetimezonetheywereborn
in,issuesofdaylightsavingstime,
considerationofleapyears,andsoforth.
Therefore,theproblemistodeterminean
approximationofageinseconds.Theprogram
willbetestedagainstcalculationsofagefrom
onlineresources.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Age in Seconds Program
Age in Seconds
The Problem
115
Theproblemistodeterminetheapproximateageofanindividualinseconds
within99%accuracyofresultsfromonlineresources.Theprogrammust
workfordatesofbirthfromJanuary1,1900tothepresent.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Age in Seconds
Problem Analysis
116
Thefundamentalcomputationalissueforthisproblemisthedevelopmentof
analgorithmincorporatingapproximationsforinformationthatisimpractical
toutilize(timeofbirthtothesecond,daylightsavingstime,etc.),while
producingaresultthatmeetstherequireddegreeofaccuracy.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Age in Seconds
Program Design
117
MeetingtheProgramRequirements
Thereisnorequirementfortheforminwhichthedateofbirthistobeentered.We
willthereforedesigntheprogramtoinputthedateofbirthasintegervalues.Also,
theprogramwillnotperforminputerrorchecking,sincewehavenotyetcoveredthe
programmingconceptsforthis.
DataDescription
Theprogramneedstorepresenttwodates,theuser’sdateofbirth,andthecurrent
date.Sinceeachpartofthedatemustbeabletobeoperatedonarithmetically,dates
willberepresentedbythreeintegers.Forexample,May15,1992wouldbe
representedasfollows:
year= 1992 month= 5 day= 15
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
118
Algorithmic Approach
PythonStandardLibrarymoduledatetimewillbeusedtoobtainthecurrentdate.
Weconsiderhowthecalculationscanbeapproximatedwithoutgreatlyaffectingthe
accuracyoftheresults.
Westartwiththeissueofleapyears.Sincethereisaleapyearonceeveryfouryears
(withsomeexceptions),wecalculatetheaveragenumberofsecondsinayearovera
four-yearperiodthatincludesaleapyear.Sincenon-leapyearshave365days,and
leapyearshave366,weneedtocompute,
numsecs_day= (hours per day) * (minsper hour) * (secsper minute)
numsecs_year = (days per year) * numsecs_day
avg_numsecs_year= (4 * numsecs_year) + numsecs_day) // 4(one extra day for leap year)
avg_numsecs_month= avgnumsecs_year// 12
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
119
Tocalculatesomeone’sageinseconds,weuseJanuary1,1900asabasis.Thus,we
computetwovalues—thenumberofsecondsfromJanuary1,1900tothegivendate
ofbirth,andthenumberofsecondsfromJanuary1,1900tothecurrentdate.
Subtractingtheformerfromthelattergivestheapproximateage,
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Notethatifwedirectlydeterminedthenumberofsecondsbetweenthedateof
birthandcurrentdate,themonthsanddaysofeachwouldneedtobecompared
toseehowmanyfullmonthsandyearstherewerebetweenthetwo.Using1900
asabasisavoidsthesecomparisons.Thus,therestofouralgorithmfollows.
120Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
121Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
The Overall Steps of the Program
Age in Seconds
Program Implementation
122
First,wedecideonthevariablesneededfortheprogram.Fordateofbirth,
weusevariablesmonth_birth,day_birth,andyear_birth.
Similarly,forthecurrentdateweusevariablescurrent_month,
current_day,andcurrent_year.Thefirststageoftheprogramassignseach
ofthesevalues.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 1—Getting the Date of Birth and Current Date
123Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
124Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 1 Testing
Weaddteststatementsthatdisplaythevaluesoftheassignedvariables.
Thisistoensurethatthedateswearestartingwitharecorrect;otherwise,
theresultswillcertainlynotbecorrect.Thetestrunbelowindicatesthatthe
inputisbeingcorrectlyread.
Enter month born (1-12): 4
Enter day born (1-31): 12
Enter year born (4-digit): 1981
The date of birth read is: 4 12 1981
The current date read is: 1 5 2010
>>>
Program Implementation
125
Nextwedeterminetheapproximatenumberofsecondsinagivenyearand
month,andtheexactnumberofsecondsinadaystoredinvariables
avg_numsecs_year,avg_numsecs_month,andnumsecs_day,respectively.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 2—Approximating the Number of Seconds in a Year/Month/Day
126Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Thelinesofcodepromptingforinputarecommentedout(lines6–9and11–14).
Sinceitiseasytocommentout(anduncomment)blocksofcodeinIDLE,wedoso;
theinputvaluesareirrelevanttothispartoftheprogramtesting
127Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Stage 2 Testing
Followingistheoutputofthistestrun.Checkingonlinesources,wefindthat
thenumberofsecondsinaregularyearis31,536,000andinaleapyearis
31,622,400.Thus,ourapproximationof31,557,600astheaveragenumber
ofsecondsoverfouryears(includingaleapyear)isreasonable.The
avg_num_seconds_monthisdirectlycalculatedfromvariableavg_numsecs_
year,andnumsecs_dayisfoundtobecorrect.
numsecs_day86400
avg_numsecs_month = 2629800
avg_numsecs_year 5 31557600
>>>
Program Implementation
128
Finally,wecompletetheprogrambycalculatingtheapproximatenumberof
secondsfrom1900toboththecurrentdateandtheprovideddateofbirth.
Thedifferenceofthesetwovaluesgivestheapproximateageinseconds.
Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Final Stage—Calculating the Number of Seconds from 1900
129Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
130Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Wedevelopasetoftestcasesforthisprogram.Wefollowthetestingstrategyof
including“average”aswellas“extreme”or“specialcase”testcasesinthetestplan.
The“correct”ageinsecondsforeachwasobtainedfromanonlinesource.January1,
1900wasincludedsinceitistheearliestdatethattheprogramisrequiredtoworkfor.
April12,1981wasincludedasanaveragecaseinthe1900s,andJanuary4,2000as
anaveragecaseinthe2000s.December31,2009wasincludedsinceitisthelastday
ofthelastmonthoftheyear,andabirthdayonthedaybeforethecurrentdateas
specialcases.Sincethesevaluesarecontinuouslychangingbythesecond,weconsider
anyresultwithinoneday’sworthofseconds(±84,000)tobeanexactresult.
131Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Theprogramresultsareobviouslyincorrect,sincetheresultisapproximatelyequal
totheaveragenumberofsecondsinamonth.Theonlycorrectresultisfortheday
beforethecurrentdate.Theinaccuracyofeachresultwascalculatedasfollowsfor
April12,1981,
((abs(expected_results–actual_results)–86,400)/expected_results)*100=
((917,110,352–518,433)–86400)/917,110,352)*100=99.93%
ExampleoutputofresultsforabirthdayofApril12,1981.
132Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Eitherouralgorithmicapproachisflawed,oritisnotcorrectlyimplemented.Sincewe
didn’tfindanyerrorsinthedevelopmentofthefirstandsecondstagesoftheprogram,
theproblemmustbeinthecalculationoftheapproximateageinlines29–37.These
linesdefinethreevariables:numsecs_1900_dob,numsecs_1900_today,and
age_in_secs.Wecaninspectthevaluesofthesevariablesafterexecutionofthe
programtoseeifanythingirregularpopsoutatus.
This program computes the approximate age in seconds of an
individual based on a provided date of birth. Only ages for
dates of birth from 1900 and after can be computed
Enter month born (1-12): 4
Enter day born (1-31): 12
Enter year born: (4-digit)1981
You are approximately 604833 seconds old
>>>
>>> numsecs_1900_dob
-59961031015
>>> numsecs_1900_today
-59960426182
>>>
133Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Clearly,thisiswheretheproblemis,sincewearegettingnegativevaluesforthetimes
between1900anddateofbirth,andfrom1900totoday.We“workbackwards”and
considerhowtheexpressionscouldgivenegativeresults.Thiswouldbeexplainedif,for
somereason,thesecondoperandofthesubtractionweregreaterthanthefirst.That
wouldhappeniftheexpressionwereevaluated,forexample,as
numsecs_1900_dob=(year_birth-(1900*avg_numsecs_year))+\
(month_birth-(1*avg_numsecs_month))+\
(day_birth*numsecs_day)
ratherthanthefollowingintendedmeansofevaluation,
numsecs_1900_dob=((year_birth-1900)*avg_numsecs_year)+\
((month_birth-1)*avg_numsecs_month)+\
(day_birth*numsecs_day)
Nowwerealize!Becausewedidnotuseparenthesestoexplicitlyindicatetheproper
orderofoperators,bytherulesofoperatorprecedencePythonevaluatedthe
expressionasthefirstwayabove,notthesecondasitshouldbe.Thiswouldalso
explainwhytheprogramgavethecorrectresultforadateofbirthonedaybeforethe
currentdate.
134Introduction to Computer Science Using Python –DierbachCopyright 2013 John Wiley and Sons Section 2.5 Age in Seconds Program
Oncewemakethecorrectionsandre-runthetestplan,wegetthefollowingresults,
Theseresultsdemonstratethatourapproximationofthenumberofsecondsina
yearwassufficienttogetwellwithinthe99%degreeofaccuracyrequiredforthis
program.Wewouldexpectmorerecentdatesofbirthtogivelessaccurateresults
giventhatthereislesstimethatisapproximated.Still,fortestcaseDecember31,
2009theinaccuracyislessthan.05percent.Therefore,wewereabletodevelopa
programthatgaveveryaccurateresultswithoutinvolvingalltheprogramlogicthat
wouldbeneededtoconsiderallthedetailsrequiredtogiveanexactresult.