Review Variables
function main()
var distance := 100
♻turtle → forward(distance)
♻turtle → back(distance)
♻turtle → right turn(90)
♻turtle → forward(distance)
♻turtle → back(distance)
end function
Reusing Variables
- It is also possible to change the value of a variable after it has been declared
So if we wanted to draw an L
function main() var distance := 100 ♻turtle → forward(distance) ♻turtle → back(distance) ♻turtle → right turn(90) distance := 50 ♻turtle → forward(distance) ♻turtle → back(distance) end function
- This is why they are called variables, the value can vary
- Note, when changing the value, don’t use
var
Also note, order still matters
Updating Variables
- But what if we want to change the size of drawing?
- Need to change two variables, one dependent on the other
- We can do better
Can update a variable using its own value
function main() var distance := 100 ♻turtle → forward(distance) ♻turtle → back(distance) ♻turtle → right turn(90) distance := distance / 2 ♻turtle → forward(distance) ♻turtle → back(distance) end function
- The horizontal line will always be half the length of the first one
So now can change the distance variable’s initial value and the entire drawing will change size
Accumulating Variables
- We can also update variables inside of a loop
Here is a neat drawing that uses a loop
function main() var distance = 100 var angle = 5 for 0 <= i < 360 / angle do ♻turtle → forward(distance) ♻turtle → back(distance) ♻turtle → left turn(angle) end for end function
- Updating variables inside a loop causes it to accumulate values
For example, changing the distance each iteration
function main() var distance = 5 var angle = 5 for 0 <= i < 360 / angle do ♻turtle → forward(distance) ♻turtle → back(distance) ♻turtle → left turn(angle) distance := distance + 5 end for end function
This means that the length of each line will be 5 units longer than the last line drawn
Quiz
- socrative.com.
- Room name ‘INQ241’