The Twelve Days of Christmas

Christmas“The Twelve Days of Christmas” is an English Christmas carol that enumerates in the manner of a cumulative song a series of increasingly grand gifts given on each of the twelve days of Christmas.

Let’s look at how we could use Python to write the lyrics of a cumulative song.

Learning Objectives


By investigating this program you will understand more how to use lists in Python and how to use loops to iterate through all the values of a list.

Remember, in Python, a list is a collection of values. It uses [square brackets].
For instance:

giftList = ["Teddy Bear","Toy car","Electric Train"]

To find out the number of items in a list we can use the len method.

giftList = ["Teddy Bear","Toy car","Electric Train"]
numberOfGifts = len(giftList)

To iterate through all the items in a list we can use a for loop.

For instance:

giftList = ["Teddy Bear","Toy car","Electric Train"]
numberOfGifts = len(giftList)

print("My Chritmas wish list to Santa:")
for i in range(0,numberOfGifts):
  print(giftList[i])

We can then use string concatenation techniques to add punctuation:

giftList = ["Teddy Bear","Toy car","Electric Train"]
numberOfGifts = len(giftList)

letterToSanta = "Dear Santa,\n\nThis is my wish list for Christmas:\n"
for i in range(0,numberOfGifts):
  letterToSanta += "\n    " + giftList[i] + ","

letterToSanta = letterToSanta[:-1] + "." #Replace last comma with a full stop.
letterToSanta += "\n\nWishing you a Merry Christmas!"

print(letterToSanta)

btnTryCodeOnline

Python Script for The Twelve Days of Christmas:


The code below is used to write the lyrics of this Christmas carol.

Challenge:


Your challenge consists of re-using this script to adapt it to create the lyrics of another cumulative song such as:

Did you like this challenge?

Click on a star to rate it!

Average rating 2.5 / 5. Vote count: 17

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!