design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.

use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs

3.3b

LO: To use variables to stand for numbers.

We're going to head back over to the interpreter in IDLE to learn about a very important concept - variables

This is going to be a very short and very basic introduction to variables because we will look at them in more detail in year 4. For now, lets think of variables as names that stand for numbers (a bit like n and m in algebra etc.)

#examples of using variables

#first we must give our variable a name and then assign a value to it
number = 9

#just writing the variable name will print out its value
number
9

#now the word (variable) 'number' stands for the number 9
#using the print() command will show this working...
print(number + 1)
10
			

You can see how variables are here used to stand in for numbers, they become useful when they can be changed

#examples of using variables

#What do you think the answer will be?
number = 7
number = 3

print(number + 7)

			

The short answer is 10. The long answer is explained below:

#examples of using variables

number = 7 #the variable 'number' is assigned the value 7
number = 3 #the variable 'number' is now assigned the value 3

#because the value was changed from 7 to 3...
print(number + 7)
#...will print out the answer 10

			

Experiment with using a range of variables to stand for numbers and include them in functions. Again, switch to IDLEs editor so you can edit any mistakes:

#Year group or class
#name
#date
#examples of using variables

#assign the variables their values
number1 = 15
number2 = 5

#write functions to use them...

def add_example():
    print(number1 + number2)

def sub_example():
    print(number1 - number2)

def multi_example():
    print(number1 * number2)

def div_example():
    print(number1 / number2)

#now call the functions...

add_example()
sub_example()
multi_example()
div_example()


			

Once children are comfortable with using variables to stand for numbers all we need now is a program to use them in, a program that could benifit from using a variable that could change, a program that uses multiplication, oh wait...

Code Examples

Resources