Variables Made Simple Jump to this section
Variables let you store values (like distances, angles, or colors) and reuse them. They make your drawings easier to change.
Using variables for distances and angles Jump to this section
import turtle
size = 100
angle = 90
t = turtle.Turtle()
t.forward(size)
t.left(angle)
t.forward(size)
Change size and angle at the top and the drawing updates everywhere you used them.
Variables in loops Jump to this section
import turtle
side = 80
count = 5
t = turtle.Turtle()
for _ in range(count):
t.forward(side)
t.left(360 / count)
This uses count to automatically decide how many steps should be taken and what the turning angle should be. Changing count creates a shape with count number of sides.
Naming and simple math Jump to this section
Variables can be updated by expressions. For example, to draw shapes with increasing size:
import turtle
t = turtle.Turtle()
size = 20
for i in range(6):
t.forward(size)
t.left(60)
size = size + 20 # this adds 20 to size, so size will increase each time the turtle moves
Exercises Jump to this section
- Create variables
widthandheightand draw a rectangle using them. - Use a variable to control the number of sides of a polygon, then change the variable to draw different polygons.
