这个函数有什么错误?

2024-09-29 00:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须创建一个函数,返回属于这个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()

Tags: 文件the函数ifiswithlineresult
1条回答
网友
1楼 · 发布于 2024-09-29 00:18:06

您提到了一个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

事实上,它用“if”语句中的条件对总体进行求和。一、 顺便说一句,我不明白“else”后面的陈述的动机。你知道吗

相关问题 更多 >