3.1.3. Variables

Variables are an important part of programming. A variable is a word or letter that represents a value that can change. It is useful if you want to use the same value in different parts of your code - declare the variable first then use it throughout your code.

Variables can make code more efficient because the variable can be changed at the beginning of your code and it automatically updates every instance of your variable in your code. You can also do maths on variables to create some interesting results.

Start with importing the turtle code and assigning the drawing function to a variable so you can write shorter code. Add a pen.forward(50) command to check you have written it properly then delete it before adding the loop code. If you get an error, read what line the error is on and see if you can spot the mistake.

Note

For this activity we start with the same basic loop used in the iteration activity then refactor the code to use variables.

import turtle
pen=turtle.Turtle()

pen.forward(50)  # Delete this line after testing

Next, create a ‘for loop’ that will repeat the code a set number of times.

for i in range (0,4):
    pen.forward(50)
    pen.right(90)

Run the code and check there are no errors. It should draw a square.

Next we add some variables. Declare them after pen=turtle.Turtle() but before for i in range(0,4):.

x=4
f=50
r=90

Now change the numbers in your loop into letters. For example pen.forward(50) becomes pen.forward(f) etc.

Run the code to check it still draws a square. If it does, try changing the variable values to see what happens e.g.

x=12
f=30
r=60

3.1.3.1. Maths

You can do maths on variables that contain numbers. As an example, if you want the forward value (f) to increase by ten after each loop you would add f=f+5. It might look like backwards maths. It is because you are assigning the answer to the question f+5 back to the original variable f. In words, you are saying f should now be equal to whatever f used to be (30) plus five more so f becomes 35 after the first loop then 40 then 45 etc.

for i in range(0,x):
    pen.forward(f)
    pen.right(r)
    f=f+5

Run the code, fix any errors and check you understand what is happening.

3.1.3.2. Next steps

Experiment with adding more commands inside the loop with varying values and with different ranges using variables.