Python Programming: An Introduction to Computer Science

(Nora) #1
8 CHAPTER1. COMPUTERSANDPROGRAMS

Typingthefirstlineimport chaostellsthePythoninterpretertoloadthechaosmodulefromthefile
chaos.pyintomainmemory. NoticethatI didnotincludethe.pyextensionontheimportline;Python
assumesthemodulewillhave a.pyextension.
AsPythonimportsthemodulefile,eachlineexecutes.It’s justasif wehadtypedthemone-by-oneat the
interactive Pythonprompt.ThedefinthemodulecausesPythontocreatethemainfunction.WhenPython
encountersthelastlineofthemodule,themainfunctionis invoked,thusrunningourprogram.Therunning
programaskstheusertoentera numberbetween0 and1 (inthiscase,I typed“.25”)andthenprintsouta
seriesof 10 numbers.
Whenyoufirstimporta modulefileinthisway, Pythoncreatesa companionfilewitha.pycextension.
Inthisexample,Pythoncreatesanotherfileonthediskcalledchaos.pyc. Thisis anintermediatefileused
bythePythoninterpreter. Technically, Pythonusesa hybridcompiling/interpretingprocess. ThePython
sourceinthemodulefileis compiledintomoreprimitive instructionscalledbytecode. Thisbytecode(the
.pyc) fileis theninterpreted.Havinga.pycfileavailablemakesimportinga modulefasterthesecondtime
around.However, youmaydeletethebytecodefilesif youwishto save diskspace;Pythonwillautomatically
re-createthemasneeded.
A moduleonlyneedsto beimportedintoa sessiononce.Afterthemodulehasbeenloaded,wecanrunthe
programagainbyaskingPythontoexecutethemaincommand.We dothisbyusinga specialdotnotation.
Typingchaos.main()tellsPythontoinvoke themainfunctioninthechaosmodule.Continuingwith
ourexample,hereis how it lookswhenwereruntheprogramwith 26 astheinput.





chaos.main()
Enter a number between0 and 1:.
0.
0.
0.
0.
0.
0.
0.
0.
0.
0.





1.7 Insidea PythonProgram


Theoutputfromthechaosprogrammaynotlookveryexciting,butit illustratesa veryinterestingphe-
nomenonknownto physicistsandmathematicians.Let’s take a lookat thisprogramlinebylineandseewhat
it does.Don’t worryaboutunderstandingeverydetailrightaway;wewillbereturningtoalloftheseideasin
thenextchapter.
Thefirsttwo linesoftheprogramstartwiththe#character:


File: chaos.py


A simple programillustrating chaotic behavior.


Theselinesarecalledcomments. They areintendedforhumanreadersoftheprogramandareignoredby
Python.ThePythoninterpreteralwaysskipsany textfromthepoundsign(#) throughtheendofa line.
Thenextlineoftheprogrambeginsthedefinitionofa functioncalledmain.


def main():


Strictlyspeaking,it wouldnotbenecessarytocreateamainfunction. Sincethelinesofa moduleare
executedasthey areloaded,wecouldhave writtenourprogramwithoutthisdefinition.Thatis,themodule
couldhave lookedlike this:

Free download pdf