dyoo at hkn.eecs.berkeley.edu
Thu Feb 3 20:29:56 CET 2005
On Thu, 3 Feb 2005, alieks laouhe wrote:
> from math import *
> while z<=2*pi:
> print cos(z)
> ok i think this is right...
This looks ok, and is probably the most straightforward way to do this.
For safety's sake, you may want to modify the top import statement
from math import *
to something a little more limited:
from math import pi, cos
The reason is because the other form, the one with the '*', pulls
everything into the current namespace, and that can be problematic in
larger programs. There's a note about it here:
There are some cute things we can do with some advanced Python. You don't
have to understand this yet, but here's a variation of your program:
>>> def stepper(start, end, step):
... i = start
... while i <= end:
... yield i
... i = i + step
>>> from math import pi, cos
>>> for z in stepper(0, 2*pi, pi/6):
... print z, cos(z)
stepper() acts like the range() function, but it can work on floating
point numbers. range (and xrange) only work on integers:
If we want to do some stepping across a range with floats, we can use the
stepper() definition above.
Best of wishes to you!
More information about the Tutor