문제

The following is what I have so far: I know I need to total the numbers in the file numberGood.txt after I change the amount to a float, but the numbers don't have variable names, ie. num1, num2 because the number of files is unknown to the program. I've solved that issue with a while-loop, but how do I get the sum of all the numbers?

*numberGood.txt is a list of various integers that I need to sum in my program.

If anyone could explain and/or give me an example, I'd be very grateful.

def main(): 
    goodNum = open("numberGood.txt",'r')
    input("Enter file name.")
    line = goodNum.readline()
    while line != "":
    amount = float(line)
    print(format(amount, '.1f'))
    line = goodNum.readline()
    print("The total is: ", amount)
    goodNum.close()
main()
도움이 되었습니까?

해결책

Use sum():

with open("numberGood.txt") as f:
    print(sum(float(line) for line in f))

Demo:

$ cat numberGood.txt 
10.01
19.99
30.0
40
$ python3
>>> with open("numberGood.txt") as f:
...     print(sum(float(line) for line in f))
... 
100.0

다른 팁

You can add them in a list and then return the sum of the list as follows:

def main(): 
    goodNum = open("numberGood.txt",'r')
    lst = []
    for line in goodNum:
        lst.append(float(line))
        print(format(lst[-1], '.1f'))
    print("The total is: ", sum(lst))
    goodNum.close()

main()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top