Variables Local and Global - New Paltz Central School District

advertisement
Variables Local and Global
Computer Science I --- Haas
Variables are one of the central concepts in computer science and one of the most powerful
tools in a programmer's toolbox. They will pop up steadily throughout the rest of the
semester.
Let’s begin with script variables, also called local variables
To create a variable use
You can click on the orange "a" to change the name. The script below will draw a regular
polygon with that number of sides. The value of sides
is used twice, first in the repeat block to say how
many times the move-and-turn combination should be
done, and again in computing the angle through which
to turn for each side.
Try running the script (by clicking the green flag)
several times to see what shapes it draws.
MAKE SURE YOU UNDERSTAND EXACTLY
WHAT IS HAPPENING IN THIS EXAMPLE.
Another place where script variables can be useful is in a program that interacts with the
user.
Get both of the above scripts running, show Haas the results and explain what is
happening.
Now let’s look at Global variables
Sometimes it's not good enough to remember a value inside one script. Instead, you need
the value available everywhere in your project. The classic example is the score in a video
game; even when no script is running, the score should be remembered.
There was a time, in the early history of programming languages, when all variables were
global. This led to a lot of bugs, because different parts of the program would use the same
name for different purposes and erase each other’s saved values. So don't use global
variables as your first choice; think whether a script
variable would work instead.
To make a global variable, you must go to the Variables
palette and click on the Make a variable button (not a
block -- you can't put it into a script!):
Click on the variables tab and click "Make a variable"
In the box that pops up - type the name of our variable "speed" (don't type the quotes).
Now you'll have blocks to use your variable.
Now create the scripts on the following page.
Write the scripts below to move an object around the screen. Notice the variable speed is
used in more than 1 script. Speed is a global variable. Complete the scripts below. MAKE
SURE YOU UNDERSTAND EXACTLY WHAT IS HAPPENING, then show Haas the
results and explain.
Download