My First Python Script

Gary Wilson Jr gdub at ece.utexas.edu
Fri Sep 16 09:59:17 EDT 2005


Ed Hotchkiss wrote:
> def ZeroThrough255():
> 	x = 0
> 	while x <= 255:
> 		if len(x) == 1:
> 			mySet = '00' + str(x)
> 		elif len(x) == 2:
> 			mySet = '0' + str(x)
> 		else:
> 			mySet = x
> 		print mySet
> 		x +=1	
> 
> ZeroThrough255()

Instead of using the while loop and a counter, you can use the range() 
function.  Using range() and string formatting you could to something like:

def ZeroThrough255():
	for num in range(256):
		print "%03d" % num

which, using a list comprehension and the string join() function, could also 
be written as:

def ZeroThrough255():
	print "\n".join(["%03d" % num for num in range(256)])



More information about the Python-list mailing list