12.07.2015 Views

Simple Nature - Light and Matter

Simple Nature - Light and Matter

Simple Nature - Light and Matter

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

calculator, but it’s a good way to design a programminglanguage so that names of functionsnever conflict.)Try it. Experiment <strong>and</strong> figure out whetherPython’s trig functions assume radians ordegrees.VariablesPython lets you define variables <strong>and</strong> assignvalues to them using an equals sign:>>> dwarfs=7>>> print(dwarfs)>>> print(dwarfs+3)710Note that a variable in computer programmingisn’t quite like a variable in algebra. Inalgebra, if a=7 then a=7 always, throughout aparticular calculation. But in a programminglanguage, the variable name really representsa place in memory where a number can bestored, so you can change its value:>>> dwarfs=7>>> dwarfs=37>>> print(dwarfs)37You can even do stuff like this,>>> dwarfs=37>>> dwarfs=dwarfs+1>>> print(dwarfs)38FunctionsSomebody had to teach Python how to dofunctions like sqrt, <strong>and</strong> it’s h<strong>and</strong>y to be ableto define your own functions in the same way.Here’s how to do it:>>> def double(x):>>> return 2.*x>>> print(double(5.))10.0Note that the indentation is m<strong>and</strong>atory. Thefirst <strong>and</strong> second lines define a function calleddouble. The final line evaluates that functionwith an input of 5.LoopsSuppose we want to add up all the numbersfrom 0 to 99.Automating this kind of thing is exactlywhat computers are best at, <strong>and</strong> Python providesa mechanism for this called a loop:>>> sum=0>>> for j in range(100):>>> sum=sum+j>>> print(sum)4950The stuff that gets repeated — the inside ofthe loop — has to be indented, just like ina function definition. Python always countsloops starting from 0, so for j in range(100)actually causes j to range from 0 to 99, notfrom 1 to 100.In algebra it would be nonsense to have a variableequal to itself plus one, but in a computerprogram, it’s not an assertion that thetwo things are equal, its a comm<strong>and</strong> to calculatethe value of the expression on the rightside of the equals, <strong>and</strong> then put that numberinto the memory location referred to by thevariable name on the left.Try it. What happens if you do dwarfs+1 =dwarfs? Do you underst<strong>and</strong> why?Exercises 909

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!