Kodewick
Start learning →

Python Turtle Sunflower

Each seed is turned 137.5 degrees (the golden angle) from the last, and spirals appear by themselves. Change that angle a little and they fall apart.

Python Turtle Sunflower
The full code (36 lines)
import turtle
import math

screen = turtle.Screen()
screen.bgcolor("lightskyblue")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)


def petal(angle, size):
    t.penup()
    t.goto(0, 0)
    t.setheading(angle)
    t.forward(70)
    t.pendown()
    t.color("orange", "gold")
    t.begin_fill()
    t.circle(size, 70)
    t.left(110)
    t.circle(size, 70)
    t.end_fill()


# the petals: 34 around
petals = 34
for i in range(petals):
    petal(i * 360 / petals - 35, 80)

# the seeds: each turned 137.5 degrees (the golden angle), further out each time
t.penup()
for i in range(320):
    r = 4 * math.sqrt(i)
    a = math.radians(i * 137.508)
    t.goto(r * math.cos(a), r * math.sin(a))
    t.dot(6, "saddlebrown" if i % 2 else "#5a3418")

How it is drawn

Seed i sits 4 * math.sqrt(i) from the centre, turned i * 137.508 degrees. The square root spreads the seeds evenly over the area instead of piling them in the middle.

137.508 degrees is the golden angle (a full turn split by the golden ratio). At this angle the seeds never line up — which is how real sunflowers grow.

math.radians turns degrees into radians; math.cos and math.sin give x and y.

Petals first, seeds after: what is drawn later lies on top.

Questions

What happens with 137 or 140?

The seeds line up in straight spokes with gaps between them. That is why nature uses the golden angle: it packs the seeds tightest.

Do I need to install math?

No, math comes with Python.

Try another