Below is an example of how you can play a musical tune using the RaspberrySTEM:
The code above is pretty simple -- we create a list of notes, and then we
use a for
loop to loop through them, play each in turn. Now,
the one big issue with this code is that each note is of a fixed
duration. But, in most songs, you have notes of varying length
(some longer and some shorter). We can modify this code so that
we can specify the length of each note independently. We do that
by creating a second list that contains the note durations, and in our for
loop, we
use both the note and the duration in our play()
function.
The zip() function provides a convenient way to combine two (or more) lists into one. Just like a zipper on jacket meshes together two rows of metal pins, the zip() function does the same things with lists. zip() will take the first element of each list and combine them together. It will then take the second element of each list and combine those together. And so on, until the shortest list runs out of elements.
For example, imagine that you have two lists, one containing the name of all the people in a household and one containing the age of all those people. The lists might look like this:
name = [Bob, Susie, Brian, Carol]
age = [31, 29, 7, 4]
If we were to zip() those two lists together:
zipped = zip(name, age)
Our resulting list ("zipped") would contain the following:
[(Bob, 31), (Susie, 29), (Brian, 7), (Carol, 4)]
The zip() function is often helpful when traversing two related lists through a for loop, as we will do below.
Here is what the code would look like: