【问题标题】:When creating a function using the turtle module, Python says my turtle name variable is not defined使用海龟模块创建函数时,Python 说我的海龟名称变量未定义
【发布时间】:2019-10-31 04:02:57
【问题描述】:

我正在制作一个使用海龟绘制正方形的函数 draw_square。它需要 (t,side_length) 其中 t 是海龟名称,side_length 是边长。但是,当使用 draw_square(dave,50) 在 thonny 中进行测试时,它说名称“dave”未定义

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

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"

【问题讨论】:

  • 你在哪里定义/设置“dave”?
  • 在交互式 shell 中的 thonny 中,我正在输入:draw_square(dave,50)
  • 这不会设置变量“dave”。
  • 哦,我以为这就是你为我创建的函数设置它们的方式——我们刚刚在课堂上介绍了这一点。我会在这个话题上做更多的研究。如果你不介意我问,我该如何设置变量?

标签: python function turtle-graphics


【解决方案1】:

你有大部分的碎片,你只需要以稍微不同的顺序排列它们:

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

【讨论】:

  • 非常感谢,效果很好!我明白我做错了什么,我现在明白了整个结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2016-03-28
  • 1970-01-01
相关资源
最近更新 更多