Drawing with Python
Be able to draw shapes with code and see loops as patterns.
Prerequisites
- CPython — the basicsrequired
Intuition
turtle is a pen that obeys commands: forward(100), right(90), penup(), pendown().
import turtle
t = turtle.Turtle()
for _ in range(4):
t.forward(100)
t.right(90) # a square
The rule for regular shapes: n sides → turn 360/n degrees each time. A triangle: 360/3 = 120°. A pentagon: 72°. A circle: 360 steps of 1°.
Code
Patterns appear when the loop variable is used in the command:
import turtle
t = turtle.Turtle(); t.speed(0)
for i in range(60):
t.forward(i * 3) # the length grows → a spiral
t.right(91) # 91 instead of 90 → the shape rotates
Swap 91 for 90 and you get a square that grows. Swap it for 120 and you get a triangular spiral. A single digit changes the whole picture.
Without turtle (in the browser, say): the same idea works with matplotlib, or by working out the coordinates yourself with sin and cos. The point is the same — a loop plus a small change per lap gives you a pattern.
Mastery means
- Draws shapes with loops
- Connects the loop variable to the pattern that appears
Sign in to do the exercises and build your mastery up.
Sources
- Python — turtle-modulen — PSF