【问题标题】:Nested "for" loops in Python-Same loop but not working-TurtlesPython 中的嵌套“for”循环 - 相同的循环但不工作 - 海龟
【发布时间】:2014-09-05 01:45:59
【问题描述】:

我只学习 Python 1 周。这是我的代码:

def board():
    colorA=input("Please choose a first color for the CheckerBoard: ")
    colorB=input("Please choose a second color for the CheckerBoard: ")
    size=int(input("Please choose a box size: "))
    num=int(input("Please choose a side length for the board: "))
    x=-250
    y=250
    c=colorA
    x=-250
    for num in range(num):
        y=y-size
        for num in range(num):
            Fbox(x,y,size,c)
            x=x+size
            if(c==colorA):
                c=colorB
            elif(c!=colorA):
                c=colorA

它几乎忽略了第一个“for”循环。

【问题讨论】:

  • 为了理智,不要为不同的目的重复使用相同的变量。
  • 对不起....我刚开始。

标签: python loops nested turtle-graphics


【解决方案1】:

核心问题是重用num 作为循环变量——使用一个不同的 变量。这种对同一变量的重用使得第一个内部循环有效地运行for num in range(0) 和第二个for num in range(1) 等(因为num 每次迭代都由外部循环重新分配。)

代码应该有类似for x in range(num) .. for y in range(num) 的循环。其中xy 是作为循环变量引入的,并且不是 像当前所做的那样在循环之外。

然后可以使用x*size+offset_x 计算位置;这也消除了手动对 x/y 进行增量的需要。按照上面的步骤逻辑,那将是

x_pos = x * size - 250
y_pos = (-1 * y) * size + 250
Fbox(x_pos, y_pos, size, c)

【讨论】:

    猜你喜欢
    • 2015-04-08
    • 2017-06-05
    • 2020-10-09
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多