



LO: To know how to use and change a variable.

Wait! You told us a variable was something that stood for a number like n or m in algebra?

Indeed, but sometimes just a part of a truth is easier to understand. Now we can find out that a variable stands for something stored in memory; it can be a number, but also*:


#declare the variable by giving it a name and then assign it a value

#a number - an integer
num = 1

#a string of words, a word or character - a string
#strings differ because they are enclosed in inverted commas
message = "hello"

#variables can also refer to expressions*
answer = (3 * 7)

answer2 = num * num


Here we can see that a variable can bee seen as the programs "memory" - what the computer can remember (contrasted with functions - what a computer can do), if we ever want a computer to remember something then we would use a variable.

* Variables can be evaluated from right to left - you work out what is the value on the right side of the = and then assign it to the variable named on the left of the =.

Allow the children to experiment with using variables and the print() function so that they can find out what they can do - and can't do with variables in IDLE interpreter.

#using variables

#declare some integer variables
num1 = 5
num2 = 7

#declare some string variables
word1 = "hello"
word2 = "goodbye"

#some experiments to try out with the print() function one at a time in IDLE
print(num1 * num2)
print(num2 - num1)
print(word1 * num1)
print(word1 + word2)
print(word2 + num2)
print(word1 * word2)


Let's look at the output from our different experiments:

*** There is also a 'float' type of variable for remembering fractional numbers e.g. 1.3. This has been left out here because trying to explain "Floating Point Arithmetic: Issues and Limitations" to 8-9 year olds fills me with dread. We will look at working with decimals later on though.

Code Examples