Week 8 · Unit 4: Variables in programming · 3 lessons
1
Boxes with names
Computing 6: Unit 4, pp. 52–67
GoalExplain what a variable is and choose the data type and a clear name for it.
New words
variable · a named place in memory where a program keeps data that can changeinteger · a data type for whole numbers, such as 7 or −3string · a data type for text, such as a word, a sentence or ‘Room 12’character · a data type for one letter, digit or symbol, such as k, 7 or #
Explanation
A variable is a named place where a program keeps a piece of data. Think of a box with a label. The label is the variable’s name and the data inside is its value. The value can change while the program runs, but the name stays the same. A program uses the name whenever it needs the data. Every variable holds one kind of data, called its data type. An integer is a whole number. A string is text, such as a word, a phrase or a mixture of letters and digits. A character is a single letter, digit or symbol. Choose names that say what the variable holds, such as score or playerName.
Data type
Used for
Examples
integer
whole numbers
7, 120, −3
string
text of any length
Hello, Room 12, x2y
character
one letter, digit or symbol
k, 7, #
Worked examples
Variable name
Value now
Data type
score
12
integer
playerName
Ana
string
grade
B
character
Here are three variables from a quiz game. Each has a clear name, a value and a data type.
Step
What happens
coins
1
the game starts
0
2
the player picks up a coin
1
3
the player picks up a coin
2
4
the player picks up a coin
3
A variable called coins starts at 0. Each time the player picks up a coin, one is added. Notice that the name stays the same but the value changes.
Poor name
Clear name
x
stars
thing2
playerName
n
numberOfLevels
Clear names make a program easier to read. The name x tells us nothing. The name stars tells us what the box holds.
Class activity
Labelled boxes (no computer): collect four small boxes or cups. Write a variable name on a sticky note for each one: stars, playerName, teamLetter and lives. Put pencils, paper clips or counters in the stars box and lives box to show the values. Write a name card for the playerName box and a letter card for the teamLetter box. Write the data type on the back of each note. Now play a short game with a partner and change the values: add a star, take away a life. Say each variable’s name and value out loud. If you have a computer or tablet, find the Variables group in Scratch and look at the make a variable button.
Practice
1
What is the data type of each value? (a) 45, (b) Kenji, (c) Q, (d) bus 5, (e) −8, (f) %.
A game stores the number of lives, the player’s name and the letter of the team the player chose, A, B or C. Choose a clear name and a data type for each.