dimanche 30 mai 2021

Adding all integers together in a file input, line by line in Python

I am trying to make a program that get the sum of all numbers in a input and print it. For example, if the file had:

3   } 3 * 5 = 15
Five
2   } 2 * 10 = 20
tEn
2   } 2 * 20 = 40
Twenty
6   } 6 * 1 = 6
onE

15 + 20 + 40 + 6 = 81

I essentially am trying to convert the words into numbers and multiply them by the integer above them and then add them up together. The problem is that I don't know how to grab all the products and add them together. Here is what I have so far:

def main():
    print(counting_money("python.txt"))


def counting_money(fileName):
    total = 0
    fin = open(fileName, "r")
    file = fin.readline()
    while file != '':
        num = int(file)
        file = fin.readline()
        face_num = file.lower()
        if face_num == "one":
            total = num * 1
        elif face_num == "five":
            total = num * 5
        elif face_num == "ten":
            total = num * 10
        elif face_num == "twenty":
            total = num * 20
        elif face_num == "fifty":
            total = num * 50
        elif face_num == "hundred":
            total = num * 100
    fin.close()
    return total

main()
        

Aucun commentaire:

Enregistrer un commentaire