def total():
the_total = 0
with open("product.txt", "r") as myFile:
for result in myFile:
r = result.split()
the_total += int(r[1]) + int(r[2])
return the_total
print(total())
def total():
t = 0
with open("product.txt", "r") as myFile:
for result in myFile:
r = result.split()
t += int(r[1]) + int(r[2])
return t
print(total()) # 480
既然选择了这个,我正在编辑包括文件关闭。
马丁·埃文斯提到:
Using with will automatically close the file for you.
您需要将每个拆分的文本条目转换为整数,并按如下方式保持运行总数:
这将显示:
使用
with
将自动为您关闭文件。你知道吗split
的结果是字符串序列,而不是整数序列。用
+
连接两个字符串。你知道吗有足够线索的互动示例:
当你得到意想不到的结果时,打开你的解释器,以交互的方式看问题通常会提供很多线索。你知道吗
正如jornsharpe在评论中提到的,您没有添加前面的值。你知道吗
由于要添加所有内容,请跟踪以前的值并添加新行(全部转换为整数)。将代码更改为:
既然选择了这个,我正在编辑包括文件关闭。 马丁·埃文斯提到:
相关问题 更多 >
编程相关推荐