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
LO: To write functions that perform operations with variables.
Now that we know that variables can stand for numbers we can move on to use them in our programs. The reason for using a variable to stand for a number is that if you need to change the program you will only have to make a change in one place:
#Year group or class #name #date #Multiplication Tables def tables_7(): print(7 * 1) print(7 * 2) print(7 * 3) print(7 * 4) print(7 * 5) print(7 * 6) print(7 * 7) print(7 * 8) print(7 * 9) print(7 * 10) print(7 * 11) print(7 * 12) tables_7()
With our multiplication program, if we had to change it - for the 9 times table for example then we would have to make 12 changes to the code. As a general rule when writing code; if you are spending a long time write something, there is probably a better way of doing it. Working smarter is better than working harder.
Let's have a look at how we could change our multiplication program using variables:
#Year group or class #name #date #Multiplication Tables with variables #declare a variable and assign* a number to it number = 9 def tables(): print(number * 1) #multiply the variable print(number * 2) print(number * 3) print(number * 4) print(number * 5) print(number * 6) print(number * 7) print(number * 8) print(number * 9) print(number * 10) print(number * 11) print(number * 12) tables()
Here you can see that by using a variable to stand for a number, if the code needs to be changed to multiply a different number then only one number in the code needs to be changed - where you change the number to assign* to the variable
Children can change their code and experiment with working out different multiplication tables.
* We will be talking alot about 'assign' when it comes to variables. The symbol = in programming does not mean 'equals' as it does in mathematics, here it means 'stands for' as in, n = 3, 'n' stands for 3 in this equation.
= can be seen as 'Mr X is our teacher' (teacher = x), but 'tomorrow our teacher is Miss Y' (teacher = y). You can see how this is different from 2 + 2 is 4 (where the word 'is' stands for equals; 2 + 2 will always be 4.