Python Programming: An Introduction to Computer Science

(Nora) #1
1.7.INSIDEA PYTHONPROGRAM 9

File: chaos.py


A simple programillustrating chaotic behavior.


print "This programillustrates a chaotic function"
x = input("Enter a numberbetween 0 and 1: ")
for i in range(10):
x = 3.9 x (1 - x)
print x


Thisversionis a bitshorter, butit is customarytoplacetheinstructionsthatcomprisea programinsideofa
functioncalledmain. Oneimmediatebenefitofthisapproachwasillustratedabove; it allowsusto(re)run
theprogrambysimplyinvokingchaos.main(). We don’t have toreloadthemodulefromthefileinorder
torunit again,whichwouldbenecessaryinthemain-lesscase.
Thefirstlineinsideofmainis reallythebeginningofourprogram.


print "This programillustrates a chaotic function"


ThislinecausesPythontoprinta messageintroducingtheprogramwhenit runs.
Take a lookat thenextlineoftheprogram.


x = input("Enter a numberbetween 0 and 1: ")


Herexis anexampleofavariable. A variableis usedtogive a nametoa valuesothatwecanrefertoit at
otherpointsintheprogram.Theentirelineis aninputstatement.WhenPythongetstothisstatement,it
displaysthequotedmessageEnter a number between0 and 1:andthenpauses,waitingforthe
usertotypesomethingonthekeyboardandpressthekey. Thevaluethattheusertypesis then
storedasthevariablex. Inthefirstexampleshownabove, theuserentered.25, whichbecomesthevalueof
x.
Thenextstatementis anexampleofaloop.


for i in range(10):

Aloopis a devicethattellsPythontodothesamethingoverandoveragain.Thisparticularloopsaysto
dosomething 10 times.Thelinesindentedunderneaththeloopheadingarethestatementsthataredone 10
times.Theseformthebodyoftheloop.


x = 3.9 x (1 - x)
print x


Theeffectoftheloopis exactlythesameasif wehadwrittenthebodyoftheloop 10 times:

x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)
print x
x = 3.9 x (1 - x)

Free download pdf