define loop statement?

Jeffrey Schwab jeff at schwabcenter.com
Sat Feb 18 15:04:03 EST 2006


David Isaac wrote:
> I would like to be able to define a loop statement
> (nevermind why) so that I can write something like
> 
> loop 10:
>     do_something
> 
> instead of
> 
> for i in range(10):
>     do_something
> 
> Possible?  If so, how?

Ruby and Smalltalk are both good at this kind of thing, since they have 
syntactic support for associating a block with each method call.  In 
Python, I think you just have to do a little more setup.  How about 
something like this?

class Loop:
	def __init__(self, n):
		self.n = n
	def __call__(self):
		self.n = self.n - 1
		return self.n != 0


if __name__ == '__main__':
	loop = Loop(10)
	while loop:
		print "OK"



More information about the Python-list mailing list