Hiya. As we are dealing with integers, why do we have "str" in the penultimate line as in
my_file.write(str(i) + "\n")
Thanking you in advance

# Add your code below!
  my_list = [i**2 for i in range(1,11)]

my_file = open("output.txt", "w")
my_file.write("Data to be written" + "\n")
for i in my_list:
    my_file.write(str(i) + "\n")

<do not remove the three backticks below>


well, we want to write all the numbers to a separate line so we use "\n" which is a string contain new line character, if we wouldn't convert i to string you would get:

TypeError: unsupported operand type(s) for +: 'int' and 'str'


And in the documentation
f.write(string) writes the contents of string to the file, returning the number of characters written.

f.write('This is a test\n')

To write something other than a string, it needs to be converted to a string first:

value = ('the answer', 42)
s = str(value)


Aaah I see, thanks mate; so, the string "\n " has precedence? My take was that the str refers/d to the items and if this were not the case, I would have expected the str to be outside the first set of brackets,(parenthesis)


Thank you for that. Does it mean that the numbers, 1 - 100, generated are strings? If so why are they not in single quotes?. Excuse my ignorance. I shall mug it up from your link . Thanks


no, but i is of type integer and "\n" is of type string. trying to add string and integer together doesn't work. So we need convert i to string, so we can concatenate i and new line so all numbers are printed on separate lines.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.