Boxes That Hold Numbers
So far every number in your programs has been fixed. A variable changes that. Give a number a name, use the name instead of the number, and one small change updates your whole drawing at once.
π‘ The idea
A variable is a named box that holds a number you can change later.
- set side 40 makes a box called side and puts 40 in it.
- Wherever a number is allowed, the name works too: forward side.
- change side by 40 adds 40 to whatever is in the box.
- change side by -10 takes ten away, because you can add a negative number.
- Use letters only for the name, and choose a name that explains itself.
π Words to know
- variable
- a named box that holds a number
- set
- put a number into the box
- change
- add to the number already in the box
π Watch this
Two squares from the same drawing code: the first 40 wide, the second 80.
set side 40 repeat 4 [ forward side right 90 ] change side by 40 repeat 4 [ forward side right 90 ]
βοΈ Your turn
- Run it and check that the second square is twice as big.
- Change set side 40 to set side 25 and run it again. Both squares change.
- Add a third square by repeating the last two lines.
- Change change side by 40 to change side by -20 and see the square shrink.
- Rename side to s everywhere, and check it still runs.
π― Challenge: Draw three squares, each one 30 bigger than the last, using a single variable.
Show me one answer
set side 30 repeat 3 [ repeat 4 [ forward side right 90 ] change side by 30 ]
Your program