使用 turtle 模块创建函数时,Python 说我的 turtle name 变量未定义

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

我正在制作一个函数 draw_square,它使用 turtle 绘制一个正方形。它需要 (t,side_length),其中 t 是海龟名称,side_length 是边长。然而,当使用 draw_square(dave,50) 在 thonny 中进行测试时,它说 name 'dave' is not defined

在创建我的函数之前尝试导入 turtle

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)

预期结果:

在给定乌龟名称和长度后绘制一个预定长度的正方形。

实际结果

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

你已经拥有了大部分的作品,你只需要稍微改变一下顺序即可:

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()