Python Programming: An Introduction to Computer Science

(Nora) #1
104 CHAPTER7. CONTROLSTRUCTURES,PART 1

>>> 3 < 4

1

>>> 3 * 4 < 3 + 4

0




"hello" == "hello"
1
"hello" < "hello"
0
"Hello" < "hello"
1





7.1.3 Example:ConditionalProgramExecution.


BackinChapter1,I mentionedthatthereareseveraldifferentwaysofrunningPythonprograms. Some
Pythonmodulefilesaredesignedtoberundirectly. Theseareusuallyreferredtoas“programs”or“scripts.”
OtherPythonmodulesaredesignedprimarilytobeimportedandusedbyotherprograms,theseareoften
called“libraries.” Sometimeswewanttocreatea sortofhybridmodulethatcanbeusedbothasa stand-
aloneprogramandasa librarythatcanbeimportedbyotherprograms.
Sofar, allofourprogramshave hada lineat thebottomtoinvoke themainfunction.


main()


Asyouknow, thisis whatactuallystartsa programrunning.Theseprogramsaresuitableforrunningdirectly.
Ina windowingenvironment,youmightruna fileby(double-)clickingitsicon.Oryoumighttypea command
likepython .py.
SincePythonevaluatesthelinesofa moduleduringtheimportprocess,ourcurrentprogramsalsorun
whenthey areimportedintoeitheraninteractive PythonsessionorintoanotherPythonprogram.Generally,
it isnicernottohave modulesrunasthey areimported. Whentestinga programinteractively, theusual
approachis tofirstimportthemoduleandthencallitsmain(orsomeotherfunction)eachtimewewantto
runit.
Ina programthatcanbeeitherimported(withoutrunning)orrundirectly, thecalltomainat thebottom
mustbemadeconditional.A simpledecisionshoulddothetrick.


if :
main()


We justneedtofigureouta suitablecondition.
Whenevera moduleis imported,Pythonsetsa specialvariableinthemodulecalled name tobethe
nameoftheimportedmodule.Hereis anexampleinteractionshowingwhathappenswiththemathlibrary.





import math
math.name
’math’





Youcanseethat,whenimported,the name variableinsidethemathmoduleisassignedthestring
’math’.
However, whenPythoncodeis beingrundirectly(notimported),Pythonsetsthevalueof name tobe
’ main ’. To seethisinaction,youjustneedtostartPythonandlookat thevalue.





name
main





So,if a moduleis imported,thecodein thatmodulewillseea variablecalled name whosevalueis the
nameofthemodule.Whena fileis rundirectly, thecodewillseethat name hasthevalue’ main ’.
A programcandeterminehow it is beingusedbyinspectingthisvariable.
Puttingthepiecestogether, wecanchangethefinallinesofourprogramstolooklike this:

Free download pdf