我必须创建一个函数来返回属于这个excel文件的所有种群的总和,但我总是得到0.什么错了? 这是文件[1]:https://i.stack.imgur.com/eUVoB.png 这是代码:
def howmanyPeople(filename):
""" howmanyPeople(String) -> int
Receives the filename as an input and returns a number
with the total population (sum of all countries) """
openFile = open(filename, 'r')
result = 0
openFile.readline() #Skips the first line (header)
for line in openFile:
populationArray = line.split(",") #Returns a list with the line divided where there is a comma
if (len(populationArray) == 3): #Checks if the name is double
result += int(populationArray[1])
else:
result += int(populationArray[2])
return result
openFile.close()
答案 0 :(得分:0)
你提到了一个excel文件,但你的代码似乎期望一个文本文件(也许这就是问题?),格式如下:
country name 1, population 1, phone number 1
country name 2, population 2, phone number 2
...
country name N, population N, phone number N
然后它确实使用&#34中的条件对人口进行求和;如果"声明。我,顺便说一句,不理解#34;其他"之后声明的动机。