A verse function generates the four lines of the Bottles of Beer song for a supplied bottle count. It returns text rather than printing it, making one verse reusable by the program that assembles the full song. section 11.0 section 11.1.2
The implementation handles the changing parts of each verse:
- Computes the next bottle count and chooses singular or plural “bottle” forms independently for the current and next counts. section 11.3.3
- Replaces a next count of zero with “No more” and joins the four formatted lines with newline characters. section 11.3.3
- Uses tests to specify expected output for valid arguments and consider behavior for missing, extra, null, nonnumeric, or otherwise adverse inputs. section 11.3.3
A reusable verse implementation
def verse(bottle): """Sing a verse""" next_bottle = bottle - 1 s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_next = 'No more' if next_bottle == 0 else next_bottle return '\n'.join([ f'{bottle} bottle{s1} of beer on the wall,', f'{bottle} bottle{s1} of beer,', 'Take one down, pass it around,', f'{num_next} bottle{s2} of beer on the wall!', ])
$ ./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!
A terminal run shows how successive calls produce verses for counts 3 through 1, including singular wording and the final “No more” line. section 11.0
