【问题标题】:Is there way to create multiple turtles using a loop?有没有办法使用循环创建多个海龟?
【发布时间】:2020-02-26 19:06:52
【问题描述】:

例如:

import turtle

num = 1
for i in range (10):
    num = turtle.Turtle()
    num += 1

我想创建 10 个从 1 到 10 的海龟。这样的代码只会在引发错误之前创建一个名为 num 的海龟(TypeError: unsupported operand type(s) for +=: 'Turtle' and 'int' )。有没有办法让 10 只海龟从 1 到 10 命名而不需要手动定义它们?

【问题讨论】:

  • 错误是什么?
  • 请分享整个错误信息。你做过研究吗?
  • 是的,只需将它们分别存储在列表或字典中即可。

标签: python turtle-graphics


【解决方案1】:
num = []
for i in range (10):
    num.append(turtle.Turtle())

?

【讨论】:

  • 这叫乌龟什么?例如,什么会取代“abc”:abc.fd(30)
  • num[0], num[1] 等等。说真的,如果你不知道,你应该得到一个 Python 教程。
【解决方案2】:
import turtle

# Create a list of turtles
turtles = [turtle.Turtle() for _ in range(10)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2016-04-30
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多