[Tutor] v.00001

Danny Yoo 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 *
> z=0
> while z<=2*pi:
> 	print cos(z)
> 	z=z+(pi/6)
>
> ok i think this is right...


Hi Alieks,

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:

###
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:

http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000



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)
...
0 1.0
0.523598775598 0.866025403784
1.0471975512 0.5
1.57079632679 6.12303176911e-17
2.09439510239 -0.5
2.61799387799 -0.866025403784
3.14159265359 -1.0
3.66519142919 -0.866025403784
4.18879020479 -0.5
4.71238898038 -1.83690953073e-16
5.23598775598 0.5
5.75958653158 0.866025403784
###


stepper() acts like the range() function, but it can work on floating
point numbers.  range (and xrange) only work on integers:

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-56

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 mailing list