liveBook · Manning

Verse

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A book-specific function that generates the text of a verse of the Bottles of Beer song for a supplied bottle count.

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

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains parameters, docstrings, returns, conditional formatting, and tests, stopping at one verse rather than full-song assembly.
Examples
Uses counts 1 and 2 in tests and demonstrates complete output beginning at count 3.
What you can do after
Apply it via a Python function that returns correctly formatted verses and verify behavior with tests.
How it connects
Connects functions with parameters and return values, string formatting, conditional expressions, and testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.