See It Believe It


#1

This is my first time with I/O files. I have "commented" on every line as I understand it. I guessed r is for read. Are my comments correct or can they be improved. Why str/item in line 8? Thank you all.


my_list = [i**2 for i in range(1,11)]
# Generates a list of squares of the numbers 1 - 10

f = open("output.txt", "w") #(# "w" for write mode on to selected file output.txt, "r" for read mode, )
 

for item in my_list:      #select each item/number and square it
    f.write(str(item) + "\n") #( write/output on to the file we have opened/selected, "\n" next line, str(item???)

f.close() #close fileReplace this line with your code.


#2

Is this what you are looking for
https://stackoverflow.com/questions/961632/converting-integer-to-string-in-python


#3

The contents of my_list are of type integer. str(item) turns the integer 1 into the string '1' so that you can concatenate it to the other string '\n'. Without str(), Python would come back with a TypeError: unsupported operand type(s) for +: 'int' and 'str'.

All of your comments are correct and it looks like you have a good understanding of what each line does.


#4

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