Domanda

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()
È stato utile?

Soluzione

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

Altri suggerimenti

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()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top