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=" ")

ご覧のとおり、ユーザーが入力した基本サイズの三角形が描画されます。

今、コードが三角形を「描く」方法を理解できません。

説明から、コードには2つのネストされたループがあり、1つは行の「描画」を担当し、もう1つは列の「描画」を担当することがわかります。

次のことを理解しようとして、これをいくつかのステップに分けてみました。

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 に答える