Python Programming: An Introduction to Computer Science

(Nora) #1
134 CHAPTER8. CONTROLSTRUCTURES,PART 2

response[0] == "y" or "Y"


Treatedasa Booleanexpression,thiswillalwaysevaluatetotrue.Thefirstthingtonoticeis thattheBoolean
operatoris combiningtwo expressions;thefirstis a simplecondition,andthesecondis a string.Hereis an
equivalentparenthesizedversion:


(response[0] == "y")or ("Y"):


Bytheoperationaldescriptionofor, thisexpressionreturnseither1 (returnedby==whenresponse[0]
is “y”)or"Y"(whenresponse[0]is nota “y”).Eitheroftheseresultsis interpretedbyPythonastrue.
A morelogic-orientedwaytothinkaboutthisis tosimplylookat thesecondexpression.It is a nonempty
string,soPythonwillalwaysinterpretit astrue.Sinceat leastoneofthetwo expressionsis alwaystrue,the
oroftheexpressionsmustalwaysbetrueaswell.
So,thestrangebehaviorofthisexampleis duetosomequirksinthedefinitionsoftheBooleanoperators.
Thisis oneofthefew placeswherethedesignofPythonhasa potentialpitfallforthebeginningprogrammer.
Youmaywonderaboutthewisdomofthisdesign,yettheflexibilityofPythonallowsforcertainsuccinct
programmingidiomsthatmany programmersfinduseful.Let’s lookat anexample.
Frequently, programspromptusersforinformationbutoffera defaultvaluefortheresponse.Thedefault
value,sometimeslistedin squarebrackets,is usedif theusersimplyhitsthe Enter key. Hereis anexample
codefragment:


ans = raw_input("Whatflavor do you want [vanilla]: ")
if ans != "":
flavor = ans
else:
flavor = "vanilla"


Exploitingthefactthatthestringinanscanbetreatedasa Boolean,theconditioninthiscodecanbe
simplifiedasfollows.


ans = raw_input("Whatflavor do you want [vanilla]: ")
if ans:
flavor = ans
else:
flavor = "vanilla"


Herea Booleanconditionis beingusedtodecidehow toseta stringvariable.If theuserjusthits Enter ,
answillbeanemptystring,whichPythoninterpretsasfalse.Inthiscase,theemptystringwillbereplaced
by"vanilla"intheelseclause.
ThesameideacanbesuccinctlycodedbytreatingthestringsthemselvesasBooleansandusinganor.


ans = raw_input("Whatflavor do you want [vanilla]: ")
flavor = ans or "vanilla"


Theoperationaldefinitionoforguaranteesthatthisis equivalenttotheif-elseversion.Remember, any
nonemptyansweris interpretedas“true.”
Infact,thistaskcaneasilybeaccomplishedina singlelineofcode.


flavor = raw_input("Whatflavor do you want [vanilla]: ") or "vanilla"


I don’t know whetherit’s reallyworthwhiletosave a few linesofcodeusingBooleanoperatorsthisway. If
youlike thisstyle,byallmeans,feelfreetouseit.Justmake surethatyourcodedoesn’t getsotricky that
others(oryou)have troubleunderstandingit.


8.6 Exercises



  1. Compareandcontrastthefollowingpairsofterms.

Free download pdf