Skip to content
Advertisement

Turtle only completes one iteration of a loop and stops at done()

I am trying Python turtle and I am facing this error:

pencolor(col) File"<string>",line 5,in pencolor turtle.Terminator

Here is my code:

from turtle import*
import colorsys

speed(0)
pensize(3)
bgcolor('black')
hue=0.0

for i in range(300):
    col=colorsys.hsv_to_rgb(hue,1,1)
    pencolor(col)
    hue+=0.005
    circle(5-i,100)
    lt(80)
    circle(5-i,100)
    rt(100)
    done()

Advertisement

Answer

The problem is calling done() in the loop. Let’s check the docs for this function:

turtle.done() Starts event loop – calling Tkinter’s mainloop function. Must be the last statement in a turtle graphics program. Must not be used if a script is run from within IDLE in -n mode (No subprocess) – for interactive use of turtle graphics.

There’s no real exceptional error in your code per se, only a logical one related to misunderstanding done. It only runs through the first iteration of the loop before blocking on done forever. When you terminate the program, turtle is still in the midst of its loop and doesn’t exit cleanly, so whatever routine it’s in at the time looks like it caused the error.

The solution is to move done outside of the loop:

from turtle import *
import colorsys

speed(0)
pensize(3)
bgcolor("black")
hue = 0.0

for i in range(300):
    col = colorsys.hsv_to_rgb(hue, 1, 1)
    pencolor(col)
    hue += 0.005
    circle(5 - i, 100)
    lt(80)
    circle(5 - i, 100)
    rt(100)

done()  # <--

This is one of many gotchas that makes turtle a bit less user-friendly for beginners than you’d think.

In the interest of avoiding other gotchas, I would avoid the * wildcard import. This dumps dozens of turtle functions into your script’s namespace which can clash with your custom-defined functions, leading to hours of debugging agony. Best practice is to use only the import turtle statement at the top of your file.

Better still is to always instantiate your turtles, t = turtle.Turtle(), and draw with t henceforth, even if it’s only a single turtle.

Finally, prefer using the long form of turtle commands unless you have difficulty typing. right and penup are much more comprehensible than rt and pu.

I also formatted your code with Black, which I recommend doing before posting.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement