python 的新手 - 处理嵌套循环。我正在尝试从 turtle import 中绘制 4 个正方形,但代码只绘制 1 个

New to python - working on nested loops. I am trying to draw 4 squares from turtle import but code only draws 1

希望有人能赐教!我对 python 非常非常陌生,无法理解这个问题!可以吗help/explain...

我相信下面的代码应该连续绘制 4 个正方形。这个练习是学习嵌套循环。它似乎在做的是在同一个点上绘制 4 个正方形,而不是向前移动将它们彼此相邻地绘制在同一条线上。

# Draw Squares across page
from turtle import *
number_of_shapes = 4

for number_of_shapes in range(1, number_of_shapes + 1) :
# Draw a Square
 for sides in range (1, 5) :
        forward (40)
        right (90)

# Move forward to start of next square
penup ()
forward (50)
pendown ()

以下作品。你的缩进有问题吗?

#Draw Squares across page
from turtle import * 
number_of_shapes = 4

for number_of_shapes in range(1, number_of_shapes + 1):

    #Draw a Square
    for sides in range(1, 5): 
        forward(40) 
        right(90)

    #Move forward to start of next square
    penup() 
    forward(50) 
    pendown()

我猜你的代码是这样的:

#Draw Squares across page
from turtle import * 
number_of_shapes = 4

for number_of_shapes in range(1, number_of_shapes + 1):

    #Draw a Square
    for sides in range(1, 5): 
        forward(40) 
        right(90)

        #Move forward to start of next square
        penup() 
        forward(50) 
        pendown()

因此,与其画正方形然后移动,不如画一条线然后移动。

您编写的解决方案看起来不错,可能存在缩进问题,这在 Python 中最为重要,因为它像其他语言使用 {} 一样呈现代码块。另一件事是,您在第一个循环中使用 number_of_shapes 作为迭代变量,这可能会导致问题,因为循环将数字 (1, 2, 3, 4, ...) 保存到此变量。您可以在一个简单的循环中尝试它是如何工作的。

for x in range(1, 5):
    print(x)

尝试将其更改为一些不同的变量 (for x in range(1, number_of_shapes + 1):) 或某些开发人员,如果他们不需要在代码中使用此变量,他们只需使用 _