在Python中查找总和

时间:2017-10-27 06:39:56

标签: python python-3.x

我正在尝试查找数字总和的代码:

-817930511,
1771717028,
4662131,
-1463421688,
1687088745

我已将它们放在一个单独的文件中,但我很困惑为什么我的代码无效。

#finding the sum
def main():
filename = input("Please enter your file name: ")
openthefile=open(filename,'r')
sum_number=0
for line in openthefile:
    for the number in line.split(","):
        sum_number=sum_number+float(numbers.strip()
print('The sum of your numbers is', sum_number)


main()

我一直在第7行代码中出现语法错误 我已经在那里改变了一些,但似乎看不出有什么问题。

2 个答案:

答案 0 :(得分:2)

使用sum简化 - 更重要的是 - strip

def main():
    # ...
    s = sum(float(l.strip(', \n')) for l in openthefile)
    print('The sum of your numbers is', s)

这会删除逗号',',空格' '(只是为了安全),以及每行末尾的换行符'\n',然后将余数转换为浮点数。< / p>

答案 1 :(得分:1)

输入文件

-817930511, 1771717028, 4662131, -1463421688, 1687088745,

代码

#finding the sum
def main():
    filename = input("Please enter your file name: ")
    openthefile=open(filename,'r')
    b=0
    for line in openthefile:
        a = ([float(x) for x in line.split(',') if x])
        b = sum(a)
    print("The sum of your numbers is", b)

main()

输出

The sum of your numbers is 1182115705.0
相关问题