# Lesson 5 # In this lesson, you will learn to use # variables and conditional statements. # General Instructions: # # This lesson contains two examples and two # exercises (A, B). # # To listen to an example, change "comment" # to "uncomment" on the "comment do" line, # then click the "Run" menu command at the # top of the Sonic Pi editor window. # When you are done with the example, turn # it off by changing "uncomment" back to # "comment," and move on to the next section # of the lesson. # # Variables: In Lesson 4, we saw that code can # be placed into blocks and repeated. If we # give values special names (variables), we can # change those values within the repeated block. # Example 1 - Variables inside a repeating block comment do use_bpm 100 myNote = 60 myTime = 1 13.times do play myNote sleep myTime myNote = myNote + 1 end end # Notice that by changing the value of the variable # inside the repeating block, we can do useful things # like playing a chromatic scale, but with fewer lines # of code than if each individual value were assigned # on a different line of code. # Exercise A # Change the code in Example 1: # 1) starting note is :G4 # 2) bpm is 120, # 3) beat length (myTime) is 1.5 times longer # 4) block repeats seven times rather than 13 # 5) scale is whole-tone (whole steps) # Conditionals. You can control the flow of # a program by checking the value of a variable and # taking action based on the state of that variable. # For example, you could increase the value of a # variable by one until it reaches a certain number, # and then increase it by two after that. # To check the value of a variable, you can use the # "if" conditional. Comparison operators such as # > (greater than), < (less than), = (equal), >= # (greater than or equal to), <= (less than or equal to) # are often used to test a variable's value. The "else" # conditional can be used to provide alternative # actions if a variable does not meet a conditional test. # Example 2 - Conditionals: comment do use_bpm 100 myNote = 60 myTime = 1 13.times do play myNote sleep myTime if myNote < 67 myNote = myNote + 1 else myNote = myNote + 2 end end end # Exercise B: # Modify Example 2 # 1) if myNote < 67 # change to if myNote > 65 # 2) myNote = myNote + 1 # change to myNote = myNote - 2 # 3) myNote = myNote + 2 # change to myNote = myNote + 1