【发布时间】:2019-07-22 20:43:56
【问题描述】:
def square_each(nums):
import math
for i in range(len(nums)):
nums[i] = nums[i]**2
def sum_list(nums):
for values in nums:
sums = sum(values)
print(sums)
def to_numbers(str_list):
numbers = [int(strings) for strings in str_list]
return numbers
def main():
print("This program computes the sum of the squares of numbers read from a file.")
filename = input("Please enter the file name:")
file = open(filename, 'r')
line = file.readline()
list1 = line.split(" ")
numbers = to_numbers(list1)
square_each(numbers)
sums = sum_list(numbers)
print("The sum of the squares of the numbers in the file is{0}".format(sums))
main()
Traceback (most recent call last):
File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 35, in <module>
File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 32, in main
sums = sum_list(numbers)
File "C:\Users\kathe\Desktop\csc161\lab_function.py", line 16, in sum_list
sums = sum(values)
TypeError: 'int' object is not iterable
我打开了一个包含字符串(数字)列表的文件。然后我使用三个函数将字符串转换为数字,对每个数字求平方,并对数字列表求和。最后一个函数 main() 包含这三个函数。但我有一个“int”对象不可迭代错误。如何在此处更正此错误?
【问题讨论】:
-
在 sum_list 函数中,删除 for 循环并返回 sum(nums)
标签: python string int typeerror