Calculate the sum of the squares of numbers from 1 to 30. The squares of the numbers are written in the file.

The 3 part problem

Need to:

  1. open file
  2. read file
  3. each square of the number is added to the sum
  4. close file

    f=open('text1.txt','r') st = f.read() S=0 for str1 in f: for i in range(1,30) S=S+i print("S=",S) f.close() 
  • Well, today this question was already there and they even began to explain something ... - MBo
  • @MBo: unfortunately there was no explanation - Oziwek
  • Read in the help or in any textbook that makes the read method of the files - andreymal
  • 2
    And in the same place read that trying to read a file opened for writing is a bad idea - andreymal
  • 2
    You have two very different things: the statement of the problem (which is extremely inaccurate) and the code given. Do you need to sum up the squares? Numbers from a file? Then why in the code for i in range (1.30)? If it's just a number from 1 to 30, then what does the file have to do here ... - Dmitry Pavlov

2 answers 2

 f = open('text1.txt', 'r') S = 0 for str1 in f: S = S + int(str1) print("S =", S) f.close() 

As you can see, I completely excluded the string

 st = f.read() 

since the st variable is never used in the future, and the string

  for i in range(1,30) 

because

 for str1 in f: 

enough (reads every line from the input file).

Then I used the int() function to translate each line from the input file to a number, and finally transferred the command

 print("S =", S) 

not the for loop (killing off), so that it is executed only once, after all the calculations.

     with open('text1.txt','w') as f: #открываете файл для ЗАПИСИ S = 0 for i in range(1,30): S += i**2 #суммируете квадраты print(str(S)) 

    Why do you need to read, and what is more, WHAT to read from the file is completely unclear