Songs with Lists

A good way to keep track of notes in a song is to use a list. Sometimes, in other languages, these structures are referred to as an array. For now, they can be thought of as the same thing but there are some behind-the-scenes differences between these two which will be covered at some other time.

A list is a collection of values that can be referred to as a single, cohesive unit. Think about how a song is a single collection comprised of several individual notes. While each note is important, it is all the notes together that make up the song.

Taking the previous example, each of the notes in the script happy_birthday are grouped in order into a list called notes. The lengths of each note are grouped, in order, into another list called lengths.

How Lists Work

To make use of data stored in a list, each element of a list is referred to by its index. The index of a list is simply the number of each element beginning with zero. So, the first element is referred to as element 0. To refer to element 0 of notes would be notes[0]. The code to refer to the fifth element, would be notes[4]. Notice how the index appears to be “off by one”. When working with lists, this can be a common mistake.

Element 0 1 2 3 4
Contents "Do" "Re" "Me" "Fa" "So"
Code alphabet = [ “Do”, “Re”, “Me”, “Fa”, “So” ]

Example script: song_with_list.

With lists, you do not have to hard code numbers for the index. A variable, like index, can stand in for a number and then that variable can be changed as the program runs. Doing this allows code to “walk” through a list.

  • Enter, save, and flash song_with_list.

 

# song_with_list

from cyberbot import *

notes = [2349.3, 2349.3, 2637.0, 2349.3, 3136.0, 2793.8]
lengths = [125, 62, 250, 250, 250, 500]
index = 0

while index <= 5:
    bot(22).tone(notes[index], lengths[index])
    index = index + 1

 

How song_with_list works

In the example above, the variable index is created after the two lists. The while loop checks the value of index each time it repeats, or iterates. As long as index is less than or equal to 5, the loop continues. Inside the loop, the tone function gets the values from each of the arrays depending on the current value of index. The second line in the loop increases the value of index by 1. This occurs over and over until the value of index becomes 6 and the loop stops. (And it’s a good thing it stops there because there is not an element number 6 in either of these lists!)

Your Turn

  • Write a script that plays the first several notes of a song that you choose.