Variables in Scratch
A variable is a “box” that remembers a value. We create a variable, build a score counter and learn to change its value.
All topics (10 of 11)
Chapter 1. Algorithm Basics
Chapter 2. Programming in Scratch
Chapter 3. Project Work
A variable is a “box” with a name, whose value can change while the program runs. It stores a number or text. In games, variables usually hold things like the score, lives left or the time.
In Scratch you create a variable in the Variables category with the “Make a Variable” button. Give it a meaningful name, for example score. The variable appears on the stage as a counter, so the player sees its current value.
The main blocks are: “set score to 0”, which gives the variable an exact value, and “change score by 1”, which changes it, here increasing it by 1 (with −1 it decreases). A game usually starts with “set score to 0”, otherwise the old value would stay.
An example is the game “Catch the apples”. Move the basket with the arrow keys, and while an apple falls use the blocks “if touching basket? then change score by 1”. As a result the score grows with every apple caught. A variable’s value can also be put into a “say” block.
Key takeaways
- A variable is a named place in memory whose value can change.
- “Set” gives it a value, and “change” increases or decreases it.
- A variable should have a meaningful name.
- A variable should be set to its starting value at the beginning of a game.
Practice tasks
- Create a variable
scoreand build a script that raises it by 1 when the sprite is clicked. - Write a script where clicking the sprite adds 1 to the score, and when it reaches 10 the sprite says “You win!”.
- Start a variable
livesat 3 and reduce it by 1 whenever the sprite touches a dangerous colour.
Review questions
Test yourself: think first, then reveal the answer.
1What is a variable?Show answerHide answer
A named place in memory whose value can change while the program runs.2Why do we set the score to 0 at the start of a game?Show answerHide answer
Otherwise the value left over from the previous game would remain.
0 of 11 topics completed
Sign in to mark