11 Bottles of Beer Song: Writing and testing functions

 

Few songs are as annoying as “99 Bottles of Beer on the Wall.” Hopefully you’ve never had to ride for hours in a van with middle school boys who like to sing this. I have. It’s a fairly simple song that we can write an algorithm to generate. This will give us an opportunity to play with counting up and down, formatting strings, and--new to this exercise--writing functions and tests for those functions!


Our program will be called bottles.py and will take one option, -n or --num, which must be a positive int (the default will be 10). The program should print all the verses from --num down to 1. There should be two newlines between each verse to visually separate them, but there must be only one newline after the last verse (for one bottle), which should print “No more bottles of beer on the wall” rather than “0 bottles”:

$ ./bottles.py -n 3
3 bottles of beer on the wall,
3 bottles of beer,
Take one down, pass it around,
2 bottles of beer on the wall!

2 bottles of beer on the wall,
2 bottles of beer,
Take one down, pass it around,
1 bottle of beer on the wall!

1 bottle of beer on the wall,
1 bottle of beer,
Take one down, pass it around,
No more bottles of beer on the wall!

In this exercise, you will

11.1 Writing bottles.py

11.1.1 Counting down

11.1.2 Writing a function

11.1.3 Writing a test for verse()

11.1.4 Using the verse() function

11.2 Solution

11.3 Discussion

11.3.1 Counting down

11.3.2 Test-driven development

11.3.3 The verse() function

11.3.4 Iterating through the verses

11.3.5 1,500 other solutions

11.4 Going further

Summary