pythonfunctionturtle-graphics

When creating a function using the turtle module, Python says my turtle name variable is not defined


I am making a function draw_square that draws a square using turtle. It takes (t,side_length) where t is turtle name and side_length is the side length. However when testing in thonny using draw_square(dave,50) it says name 'dave' is not defined

Tried importing turtle before creating my function

import turtle
def draw_square(t, side_length):
        """Use the turtle t to draw a square with side_length."""

        t=turtle.Turtle()
        t.forward(side_length)
        t.right(90)
        t.forward(side_length)
        t.right(90)
        t.forward(side_length)
        t.right(90)
        t.forward(side_length)
        t.right(90)

Expected result:

draws a square of predetermined length after giving turtle name and length.

Actual result:

"Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
NameError: name 'dave' is not defined"

Solution

  • You have most of the pieces, you just need to arrange them in a slightly different order:

    import turtle
    
    def draw_square(t, side_length):
        """ Use the turtle t to draw a square with side_length. """
    
        t.forward(side_length)
        t.right(90)
        t.forward(side_length)
        t.right(90)
        t.forward(side_length)
        t.right(90)
        t.forward(side_length)
        t.right(90)
    
    dave = turtle.Turtle()
    
    draw_square(dave, 50)
    
    turtle.done()