I need to read the input file (input.txt), which contains one line of integers (13 34 14 53 56 76), and then calculate the sum of the squares of each number.
This is my code:
def main():
print("\nThis is the last function: sum_of_squares")
print("Please include the path if the input file is not in the root directory")
fname = input("Please enter a filename : ")
sum_of_squares(fname)
def sum_of_squares(fname):
infile = open(fname, 'r')
sum2 = 0
for items in infile.readlines():
items = int(items)
sum2 += items**2
print("The sum of the squares is:", sum2)
infile.close()
main()
If each number is on a separate line, it works fine.
But I can’t figure out how to do this when all the numbers are on the same line, separated by a space . In this case, I get an error:ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'
source
share