[Tutor] file i.o

Daniel Ehrenberg littledanehren at yahoo.com
Sun Jan 25 14:42:16 EST 2004


> from os import *
> 
> output = open('numbers','wa')
> counter = 0
> while (counter<10):
>      output.write("%f\n" % (counter))
>      print counter
>      counter = counter + 1
> Kim

I think someone already corrected you on the from os
import * command, so I'll just talk about the while
loop. In Python, while loops aren't used with counters
like for loops are in other languages. In Python, we
still use for loops, but they are used to iterate over
a range(). In this case, we'd iterate over range(0,
10). Here's how I would write the loop:

for counter in range(0, 10):
    output.write('%f\n' % counter)
    print counter

That's two lines shorter and a lot easier to read.

Daniel Ehrenberg

__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free web site building tool. Try it!
http://webhosting.yahoo.com/ps/sb/



More information about the Tutor mailing list