Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python turtle function – receiving an error I can't make sense of

When running the below code I am receiving this error. Anyone any ideas, I have followed an example set by a tutor and made it my own but mine doesn’t run.

Traceback (most recent call last):
  File "main.py", line 74, in <module>
    timmy.color(random_color)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/turtle.py", line 2217, in color
    pcolor = self._colorstr(pcolor)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/turtle.py", line 2697, in _colorstr
    return self.screen._colorstr(args)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/turtle.py", line 1153, in _colorstr
    if len(color) == 1:
TypeError: object of type 'function' has no len()
import turtle
import random

timmy = turtle.Turtle()
turtle.colormode(255)
timmy.shape("turtle")
timmy.color("red")

turtle_heading = [0, 90, 180, 270]

def random_color():
  r = random.randint(0, 255)
  g = random.randint(0, 255)
  b = random.randint(0, 255)
  random_color(r, g, b)
  return random_color


for i in range(200):
  timmy.setheading(random.choice(turtle_heading))
  timmy.color(random_color)
  timmy.forward(30)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You seem to have gotten variables and functions confused. Maybe from VBA or similiar.

In python, a variable is either a function or a value, never both.

At then end of your random_color() you call random_color with the arguments (r,g,b), which will give you an error when executed, as your function doesn’t take arguments. Then you return the function itself.

What you probably wanted to do was to return the tuple (r, g, b) which you can do by replacing the last two lines of the function with return (r, g, b) and then calling it with random_color() in your timmy.color().

Your current error there happens because you pass it the function without executing it, so it complains that the function-type object you passed has no length (as that is required by timmy.color)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading