0

首先是代码:

# the star triangle
# the user gives a base length, to print a triangle

base_length = int(input("enter the base of the triangle: "))
for row in range(base_length):
    print()
    for column in range (row + 1):
        print("*", end=" ")

如您所知,它将绘制一个三角形,其基本大小与用户输入的任何内容相同。

现在,我无法理解代码如何“绘制”三角形。

从解释中,我知道代码有两个嵌套循环,一个负责“绘制”行,另一个负责“绘制”列。

我尝试通过尝试理解以下内容将其分解为多个步骤:

base_length = int(input("enter the base of the triangle: "))
for row in range(base_length):
    print("*")
#    for column in range (row + 1):
#        print("*", end=" ")

这没有帮助。我不明白为什么它在多行而不是在同一行中打印“*”。

其余的,无论我怎么想,对我来说都毫无意义。我所理解的大约是“+ 1”,它让你使用范围内的最后一个数字,因为如果没有指定,Python 将不会使用范围内的最后一个数字。

我想我只是没有得到 for 循环,当你嵌套了 for 循环时,我真的有问题。

4

1 回答 1

1

我相信理解代码的问题会导致不同的行为print()

  • print("*")- 打印“ *”和 endline(转到下一行),
  • print("*", end=" ")- 打印“ *”并以空格结束输出(“ ”而不是新行),
  • 当你这样做时print(),它会打印“nothing”(或空字符串,如果这更容易理解的话)并以新行结束(这使得文本进入下一行)。

对理解代码有帮助吗?如果没有,这是代码中的解释:

# User gives the integer, being a number of the rows
base_length = int(input("enter the base of the triangle: "))

# This is a loop on the integers, from zero (0) to the (base_length - 1)
# Which means the number of iterations equals exactly base_length value:
for row in range(base_length):
    print()  # Prints just a new line

    # First uses "row" as a base, it will be the number of the asterisks
    # Then it iterates on the list of integers (column equals zero, then 1 etc.)
    for column in range (row + 1):

        # Prints asterisk and ends the output with space instead of new line:
        print("*", end=" ")
于 2012-10-09T01:50:35.610 回答