您的代码有多个问题。你犯的错误是因为你:total=sum(line_str[0:len(element)])
元素是一个整数,它在range()生成的值上循环。
您有total选项并在for循环中打印。您为每个元素而不是每一行调用print,因此无法获得所需的输出。
这个:line_str[0:0]将得到一个空列表,而使用这个:line_str[0:element]将永远不会包含最后一个元素
这是一个只需少量更改即可工作的版本:#Ask the user to input a file name
# file_name=input("Enter the Filename: ") # temporary commented out for easier testing.
file_name = "input.txt"
#Opening the desired file to read the content
infile=open(file_name,'r')
#Importing the math library
import math
#Iterating for the number of lines in the file
for line in infile:
#Converting the file to a list row by row
line_str=line.split()
for element in range(len(line_str)):
line_str[element]=float(line_str[element])
line_str[element]=math.pow(line_str[element],2)
total=sum(li