[Tutor] Question

Alan Gauld alan.gauld at btinternet.com
Thu Jul 12 22:54:24 CEST 2007

"Que Prime" <queprime at gmail.com> wrote 

>   Here is what I have so far but can't seem to get the loop and
> write correct.

I suspect you have used another language before and 
Python's for loop is foxing you.

> print "Creating txt file"
> tfile = open("25.txt", "w")
> for i in range(25):
>    x = int(1)

You don;t need to convert to an int, i is already an int.
But worse, you are here converting the number 1 to 
an int every time through the loop. I don't think thats 
what you want! range(25) will produce a list of numbers 
from 0 to 24. The for loop will set i to each number in 

>    tfile.writelines("x\n")

And writelines expects a list of strings but you are 
giving it one string. You only need write() here. And 
of course you don't need x so you can just write 
the string version of i: str(i) plus a new line (\n)

>    x += 1

And you don't need this at all because the loop 
will automatically get the next number.

> tfile.close()

Try those changes, it should simplify things significantly.

You might find a quick read through my loops and file 
handling topics useful too.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list