1.6.THEMAGICOFPYTHON 7
Canyouseewhatis happeninghere?Whenweusegreetwecansenddifferentnamestocustomizethe
result.We willdiscussparametersin detaillateron.Forthetimebeing,ourfunctionswillnotuseparameters,
sotheparentheseswillbeempty, butyoustillneedtoincludethemwhendefiningandusingfunctions.
Oneproblemwithenteringfunctionsinteractivelyat thePythonpromptlike thisis thatthedefinitionsgo
awaywhenwequitPython.If wewanttousethemagainthenexttime,wehave totypethemalloveragain.
Programsareusuallycreatedbytypingdefinitionsintoa separatefilecalledamoduleorscript. Thisfileis
savedona disksothatit canbeusedoverandover again.
A modulefileis justa text file,andyoucancreateoneusingany programforeditingtext,like a notepador
wordprocessorprogram(providedyousave yourprogramasa “plaintext”file).A specialtypeofprogram
knownasaprogrammingenvironmentsimplifiestheprocess. Aprogrammingenvironmentis specifically
designedtohelpprogrammerswriteprogramsandincludesfeaturessuchasautomaticindenting,colorhigh-
lighting,andinteractive development.ThestandardPythondistributionincludesa programmingenvironment
calledIdlethatyoumayuseforworkingontheprogramsinthisbook.
Let’s illustratetheuseofa modulefilebywritingandrunninga completeprogram. Ourprogramwill
illustratea mathematicalconceptknownaschaos.Hereis theprogramaswewouldtypeit intoIdleorsome
othereditorandsave ina modulefile:
File: chaos.py
A simple programillustrating chaotic behavior.
def main():
print "This programillustrates a chaotic function"
x = input("Entera number between 0 and 1: ")
for i in range(10):
x = 3.9 x (1 - x)
print x
main()
Thisfileshouldbesavedwithwiththenamechaos.py. The.pyextensionindicatesthatthisisa
Pythonmodule.Youcanseethatthisparticularexamplecontainslinesto definea new functioncalledmain.
(Programsareoftenplacedina functioncalledmain.)Thelastlineofthefileis thecommandtoinvoke
thisfunction.Don’t worryif youdon’t understandwhatmainactuallydoes;wewilldiscussit inthenext
section.Thepointhereis thatoncewehave a programina modulefile,wecanrunit any timewewant.
Thisprogramcanberunina numberofdifferentwaysthatdependontheactualoperatingsystemand
programmingenvironmentthatyouareusing.If youareusinga windowingsystem,youcanruna Python
programby(double-)clickingonthemodulefile’s icon. Ina command-linesituation,youmighttypea
commandlikepythonchaos.py. If youareusingIdle(oranotherprogrammingenvironment)youcan
runa programbyopeningit intheeditorandthenselectinga commandlikeimport,run, orexecute.
Onemethodthatshouldalwaysworkis tostartthePythoninterpreterandthenimportthefile.Hereis
how thatlooks.
import chaos
This program illustratesa chaotic function
Enter a number between0 and 1:.
0.
0.
0.
0.
0.
0.
0.
0.
0.
0.