In this lab, you will use local and global variables to store information.
On this page, you will begin to develop a number guessing game that uses a local variable to keep track of a secret number.
number guessing game that will contain the code for the game. Leave the Block Editor open.
In a number-guessing game, the player tries to guess the computer's secret number. The computer needs a way to store the secret number in a variable so that it can compare it to the player's guesses.
A variable is like a labeled box that can hold one value at a time, such as one word, one costume, or one list (which can contain many things). You can look at what's inside as many times as you want.
script variables block into the Scripting Area. You can find it in the Variables palette.
script variables block (the way you drag an input) and placing it where you need it in your code.
to set the initial value of secret number to a random number from 1 to 10. The set menu lets you select which variable to set. set block only when you snap it somewhere after the script variables block.
secretNumber = 7
(Python uses one equals sign to set the value of a variable.)
would be written as secretNumber ← 7or
.
Script variables are a kind of local variable; they work only within the script where they're created. If you drag one into a different script, it won't work. You've seen two kinds of local variables before: inputs to blocks and for counters.
You have created variables as inputs to blocks that you made:
You have used the counter variable that the for block gave you:
A local variable can be set or used only in the environment in which it is defined. This term includes inputs to procedures and variables created by the for or script variables block.
In algebra, a variable is sometimes used for something whose value you don't know yet, and the goal is to find out its value. In programming you decide the values of variables.
, then bananas will hold the value 2 and have no memory of it having come from apples. This is why a ← a * 2means something. (Suppose a = 8. First compute the value of
a * 2, namely 16, and then replace the old value of a with 16). Up to now, the only variables you've used are input variables, and you never assign a value to an input because the value is given by the code that calls it. But a script variable won't have a value until you give it one with
set.a ← 3 b ← a a ← 4 DISPLAY(b)
b ← ais done).
b ← ais done); b doesn't remember that the 3 came from a so it doesn't change when a is changed.
set command sets the value of the variable k to the value k – m, not m – k.