[Tutor] Loopy question

Yigal Duppen yduppen@xs4all.nl
Thu, 18 Jul 2002 21:30:57 +0200


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Thursday 18 July 2002 06:07, Mike Yuen wrote:
> This is a real newbie question.
> I got a question about a step in a loop.  I want to make my step really
> small for a problem i'm testing.  However, the interpreter says my step in
> the for loop (0.01) is a zero step for range.

That's correct. 
The interpreter tries to evaluate the step to an integer, something you cannot 
influence. And since int(0.01) == 0, range complains.

So you basically have two options:
1) step like you would step 20 years ago
2) use generators (but only for python2.2)

Example 1)

x = 2
while x < 5:
	print x 	# or whatever you want here :)
	x += 0.01


Example 2)
(more reusable, much nicer)

def frange(start, stop, step=1):
	"""Returns an iterator, just like xrange, that accepts floating point
	steps.
	"""
	x = start
	while x < stop:
		yield x
		x += step


for x in frange(2, 5, 0.01):
	print x



I personally prefer the second option for the following reasons:
*) the counting complexity is hidden away in the frange function
*) the entire loop looks much more pythonic
However, this example only works in python2.2 (and above); in python2.2 you 
_must_ put an "from __future__ import generators" statement at the beginning 
of your script.

YDD
- -- 
.sigmentation Fault
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE9NxdxLsKMuCf5EdwRAjc2AKCDWgj7dCeJtACTYfDjIf0lijvKhACgpgn+
czBnraVYUtABnzPZ3cX8Le8=
=o+ZU
-----END PGP SIGNATURE-----