Snap Lesson 7: Variables
In this lesson we will learn how to use variables in our program

IMG_1600

 First we need to lean what a variable is. Variables are a way to save a number so we can use it later. So for instance if I make a variable, name it x, and set x to 10, than anywhere I use the variable x in my program, it will replace it with the value 10. Lets see how we can create a variable.

Now we have made a variable named x that is equal to 10. So what can we do with this variable? Lets say that we have the code to move in a square. Right now each side moves at 100 speed for 2 seconds. Then we want to change it to 5 seconds. To do so normally we would have to change the wait at each step of the way, but if we use a variable we only need to change the code in one place. It makes it much quicker to change the time for all:

 

Also variables do not always need to be the same value, we can set sideTime to different values as we go, or even use some math to do it for us. What if we wanted the CoDrone to move one less second on each side, but still be able to change the total time with one value. We can subtract one from sideTime after each movement:

This will have the CoDrone move forward for sideTime, then for the next step move for sideTime-1 seconds. Then each step along the way it moves for one fewer second, making a spiral inwards. So variables change change values as the code goes on.

 

Activity: Multi-Sized Figure-Eight

Challenge Rules:

  1. Use your code from the previous lesson that moves in a figure-eight with the LEDs
  2. Change the move time of each side to a variable so allow for easy size changing
  3. Then adjust the move time to make several sized figure-eights with only changing one number