【问题标题】:Iteration issue when coding for Turtle module为 Turtle 模块编码时的迭代问题
【发布时间】:2025-11-13 13:50:09
【问题描述】:

我不断收到一条错误消息,指出“i”是一个未使用的变量,但我正在使用它来迭代一个循环,该循环具有取决于用户输入 (numShapes) 的变量范围。当它是一个整数值时,为什么python不接受该变量?

***此代码用于调用 turtle 模块的两个绘图函数之一,随机放置可变数量 (numShapes) 的不同大小和位置的绘图。

import random
import turtle, BoundingBox
from TurtleShapes import drawOneSquare
from TurtleShapes import drawOneShape

x = turtle.Turtle()

def drawEverywhere(x, func):      
    numShapes = int(input("How many shapes?"))
    for i in range(numShapes):
        x.penup()
        x.goto((random.randint(-1150,1150), random.randint(-550,550))      

        for i in range(numShapes):
            func(turtle, size))
                size = random.randint(10,40)

if __name__ == '__main__':
    win = turtle.Screen()
    BoundingBox.drawBoundingBox()

    ### Decide which shape ###
    input("Which shape? 's' for square or 'c' for circle")
        if input == 's':
            drawEverywhere(turtle, drawOneSquare)
        elif input == 'c':    
            drawEverywhere(turtle, drawOneShape)   
        else:
            print('invalid input') 

    win.exitonclick()

【问题讨论】:

    标签: loops iteration turtle-graphics


    【解决方案1】:

    当我们有这样的循环时:

    for i in range(10):
        print(":-)")
    

    一些 Python 代码检查器会将变量 i 标记为未使用,但它的值从未使用过。解决此问题的一种常见方法是使用 Python 的通用“一次性”变量名称 _

    for _ in range(10):
        print(":-)")
    

    看看这是否会抑制您收到的 unused 警告。这是 Python 中 _ 变量的几种用法之一。

    关于您的代码的其他说明:

    x.goto((random.randint(-1150,1150), random.randint(-550,550))
    

    它缺少一个右括号,并且不需要额外的左括号来创建一个元组——它可以简化为:

    from random import randint
    # ...
    x.goto(randint(-1150, 1150), randint(-550, 550))
    

    这段代码会给你带来麻烦:

    func(turtle, size))
        size = random.randint(10,40)
    

    由于不平衡的括号,不合理的缩进和执行顺序。你可能想要:

    size = random.randint(10, 40)
    func(turtle, size)
    

    【讨论】:

    • 谢谢!我没有收到`size = random.randint(10,40)`的无效语法错误消息你知道为什么会这样吗?
    • @SydneyBallard,如果你使用了我提到的from random import randint,那么语法就是size = randint(10, 40)。否则,我看不到语法错误的原因,您可能会使用当前完整的代码打开一个新问题。
    最近更新 更多