Beginner Python: Accumulator loop function

Jr. picture Jr. · Sep 21, 2013 · Viewed 8.9k times · Source

I am a beginner in python and I have an assignment where I am required to print out a song using a definite loop, a string accumulator, and concatenation. The issue is, I am able to print out each stanza in a definite loop (the song assumes a 3 stanza song so the range is set to 3) and before each stanza is created, it asks for the user to input an animal and it's sound (its old macdonald). I achieved completing the first part of the assignment which is to have each stanza printed out after the user gave their input but the second part asks for all of the stanzas (3 in total) to be concatenated into the entire song. So the end result would be the individual stanzas placed together into one song. The problem is, how do I use an accumulator given what I have to update the song and then output the entire song at the end? Attached is my code: (Note this is python 2.7.5)

def main():


    for stanza in range(3):
        animal = raw_input("What animal? ")
        animalSound = raw_input("What sound does a %s make? " %(animal))

        print
        print "\t Old MacDonald had a farm, E-I-E-I-O,"
        print "And on his farm he had a %s, E-I-E-I-O" %(animal)
        print "With a %s-%s here - " %(animalSound, animalSound)
        print "And a %s-%s there - " %(animalSound, animalSound)
        print "Here a %s there a %s" %(animalSound, animalSound)
        print "Everywhere a %s-%s" %(animalSound, animalSound)
        print "Old MacDonald had a farm, E-I-E-I-O"
        print

Answer

Robᵩ picture Robᵩ · Sep 21, 2013

By "accumulator", I assume you mean the pattern in which you continuously add to a previous string. This can be had with the operator +=.

By "concatenation", I assume you mean the string operator +.

By your own rules, you aren't allowed the % operator.

You might do it this way:

song = ''  # Accumulators need to start empty
for _ in range(3):  # Don't really need the stanza variable
    animal = raw_input("What animal? ")
    animalSound = raw_input("What sound does a %s make? " %(animal))

    song += "Old MacDonald had an errno. EIEIO\n"
    song += "His farm had a " + animal + " EIEIO\n"
    song += "His " + animal + "made a noise: " + animalSound + "\n"
print song

etc.

I believe this is what your assignment calls for, but realize that this would not be considered "good" or "Pythonic" code. In particular, string accumulation is inefficient -- prefer list comprehensions and str.join().