Search code examples
pythonsumtxt

Old MacDonald Sum of total animals should be 44


My issue is that I can't get the total amount of animals from my animals.txt file

2 pig oink
3 duck quack
4 horse neigh
5 lamb baa
6 chickens cluck
7 dog woof
8 cat meow
9 cow moo
----------
44

to show 44 total animals in my python program. Below is what I have.

def write_verse(vfile,animals): #function to write the animals into a verse.txt file
    with open('animals.txt', 'r') as f:
        result = sum(map(int, vfile))
    count = 1
    for animal in animals:  #loop to iterate through all animals
        amount = animal[0]
        name = animal[1]
        noise = animal[2]
        format1 = f'Verse :{count}\n'   #formatting strings
        format2 = f'Old MacDonald had a farm\n'
        format3 = f'E-I-E-I-O\n'
        format4 = f'And on his farm he had {amount} {name}\'s\n'
        format5 = f'With a {noise} {noise} there\n'
        format6 = f'And a {noise} {noise} here\n'
        format7 = f'Here a {noise},there a {noise}\n'
        format8 = f'Everywhere a {noise} {noise}\n'
        string =str(format1+format2+format3+format4+format3+format5+format6+format7+format8+format2+format3)
        vfile.write(string+"\n")    
        print(string)
        count+=1
    vfile.write("Old MacDonald has a total of {0} animals".format(count-1))
    print(f"Old MacDonald had a total of {result} animals")


try:
    file = open('animals.txt','r')
except FileNotFoundError as a:
    print(a)
contents = file.readlines()

animals_list = []
for line in contents:
    line = line.rstrip("\n")
    animals_list.append(line.split(" "))

file.close()

try:
    vfile = open("verses.txt","w+")
except:
    pass
write_verse(vfile,animals_list)
vfile.close()

This is what happens when I run it -

Verse :1 Old MacDonald had a farm E-I-E-I-O And on his farm he had 2 pig's E-I-E-I-O With a oink oink there And a oink oink here Here a oink,there a oink Everywhere a oink oink Old MacDonald had a farm E-I-E-I-O

Verse :2 Old MacDonald had a farm E-I-E-I-O And on his farm he had 3 duck's E-I-E-I-O With a quack quack there And a quack quack here Here a quack,there a quack Everywhere a quack quack Old MacDonald had a farm E-I-E-I-O

Verse :3 Old MacDonald had a farm E-I-E-I-O And on his farm he had 4 horse's E-I-E-I-O With a neigh neigh there And a neigh neigh here Here a neigh,there a neigh Everywhere a neigh neigh Old MacDonald had a farm E-I-E-I-O

Verse :4 Old MacDonald had a farm E-I-E-I-O And on his farm he had 5 lamb's E-I-E-I-O With a baa baa there And a baa baa here Here a baa,there a baa Everywhere a baa baa Old MacDonald had a farm E-I-E-I-O

Verse :5 Old MacDonald had a farm E-I-E-I-O And on his farm he had 6 chickens's E-I-E-I-O With a cluck cluck there And a cluck cluck here Here a cluck,there a cluck Everywhere a cluck cluck Old MacDonald had a farm E-I-E-I-O

Verse :6 Old MacDonald had a farm E-I-E-I-O And on his farm he had 7 dog's E-I-E-I-O With a woof woof there And a woof woof here Here a woof,there a woof Everywhere a woof woof Old MacDonald had a farm E-I-E-I-O

Verse :7 Old MacDonald had a farm E-I-E-I-O And on his farm he had 8 cat's E-I-E-I-O With a meow meow there And a meow meow here Here a meow,there a meow Everywhere a meow meow Old MacDonald had a farm E-I-E-I-O

Verse :8 Old MacDonald had a farm E-I-E-I-O And on his farm he had 9 cow's E-I-E-I-O With a moo moo there And a moo moo here Here a moo,there a moo Everywhere a moo moo Old MacDonald had a farm E-I-E-I-O

Old MacDonald had a total of 0 animals

Process finished with exit code 0


Solution

  • You're printing result, but result isn't calculated correctly. There are kind of a lot of issues with your code, and somebody has already pointed out how to fix the problem. So instead, I'm going to make some suggestions for writing cleaner, more organized code which can make debugging issues much easier:

    # Use a template literal string formatted almost exactly as 'WYSIWYG'
    VERSE = """
    Verse: {verse}
    Old MacDonald had a farm
    E-I-E-I-O
    And on his farm he had {amount} {animal}s
    With a {noise} {noise} here
    And a {noise} {noise} there
    Here a {noise} there a {noise}
    Everywhere a {noise} {noise}
    Old MacDonald had a farm
    E-I-E-I-O
    """
    
    
    # Separate helper function to read in your data
    def read_file(path):
        data = []
        with open(path, "r") as file:
            for line in file.readlines():
                amount, animal, noise = line.strip().split()
                data.append({"animal": animal, "noise": noise, "amount": int(amount)})
        return data
    
    
    # Write any number of verses given a list of animals
    def sing_old_macdonald(animals):
        song = ""
        total = 0
        for verse, animal in enumerate(animals, 1):
            song += VERSE.format(verse=verse, **animal)
            total += animal["amount"]
        return song, total
    
    
    # Main script
    if __name__ == "__main__":
        animals = read_file("animals.txt")
        song, total_animals = sing_old_macdonald(animals)
        print(song)
        print(f"Old MacDonald has {total_animals} animals on his farm")
    

    Trimmed output:

    .
    .
    .
    
    Verse: 8
    Old MacDonald had a farm
    E-I-E-I-O
    And on his farm he had 9 cows
    With a moo moo here
    And a moo moo there
    Here a moo there a moo
    Everywhere a moo moo
    Old MacDonald had a farm
    E-I-E-I-O
    
    Old MacDonald has 44 animals on his farm