Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python求和_Python_Python 3.x - Fatal编程技术网

用Python求和

用Python求和,python,python-3.x,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 o

我正在编写一个代码,试图找到这些数字的总和:

-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行出现语法错误 我在那里也做了一些更改,但似乎看不出有什么问题。

输入文件

-817930511, 1771717028, 4662131, -1463421688, 1687088745,
代码

输出

The sum of your numbers is 1182115705.0
输入文件

-817930511, 1771717028, 4662131, -1463421688, 1687088745,
代码

输出

The sum of your numbers is 1182115705.0
简化使用,更重要的是:

这将去掉每行末尾的逗号、空格和换行符,然后将其余部分变成浮点数。

简化了使用,更重要的是:


这将去掉每行末尾的逗号“
”、”
、空格“
(为了安全起见)和换行符“\n””,然后将剩余部分变成浮点数。

应该是
number.strip()
对于…中的数字
我已经更改了您的建议,但现在它表明在7ht行中突出显示数字的语法无效。首先,缩进是错误的,至少在您提供的示例中是错误的。正如@VanPeer提到的数字
将抛出一个错误。这是错误的语法。同时调用
numbers.strip()
将抛出NameError。代码中没有任何名为
numbers
的变量。并且在number.strip()之后缺少了一个)子句,该子句将强制转换为float。它应该是
number.strip()
对于…中的数字
我已经更改了您的建议,但现在它表明在7ht行中突出显示数字的语法无效。首先,缩进是错误的,至少在您提供的示例中是错误的。正如@VanPeer提到的数字
将抛出一个错误。这是错误的语法。同时调用
numbers.strip()
将抛出NameError。您的代码中没有任何名为
numbers
的变量。并且在number.strip()之后缺少一个)子句,该子句将强制转换为float。