美文网首页
读取文件中的数字并返回所有数字的总合

读取文件中的数字并返回所有数字的总合

作者: 极光火狐狸 | 来源:发表于2018-10-02 14:03 被阅读13次

源码: main.py

# -.- coding:utf-8 -.-
# 文件: 读取文件中的数字并返回所有数字的总合.
from __future__ import print_function


def sum_file(path):
    """
    :return: integer
    """
    total = 0
    with open(path) as f:
        for i in f:
            i = i.strip()
            i = int(i)
            msg = "i({:<2}) + total({:<2}) = {}"
            print(msg.format(total, i, total + i))
            total += int(i)
    return total


def main():
    sum_file("numbers.txt")


if __name__ == '__main__':
    main()

# output:
# i(0 ) + total(1 ) = 1
# i(1 ) + total(2 ) = 3
# i(3 ) + total(3 ) = 6
# i(6 ) + total(4 ) = 10
# i(10) + total(5 ) = 15
# i(15) + total(6 ) = 21
# i(21) + total(7 ) = 28
# i(28) + total(8 ) = 36
# i(36) + total(9 ) = 45

 
 

源文件: numbers.txt

1
2
3
4
5
6
7
8
9

相关文章

网友评论

      本文标题:读取文件中的数字并返回所有数字的总合

      本文链接:https://www.haomeiwen.com/subject/uitaoftx.html