Python Code Example: triangle pattern

This Python code snippet generates a pattern of numbers printed in a specific way. It consists of two nested loops within two separate outer loops.

Code Example

rows = 8

for i in range(0, rows + 1):
    for j in range(1, i):
        print(j, end=" ")
    print()

for i in range(rows + 1, 0, -1):
    for j in range(1, i):
        print(j, end=" ")
    print()

Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 

Code Explanation

Initial Setup

rows = 8
  • A variable rows is initialized with the value 8. This determines the number of rows for the pattern.

First Part: Ascending Pattern

for i in range(0, rows + 1):
    for j in range(1, i):
        print(j, end=" ")
    print()
  • Outer Loop (for i in range(0, rows + 1)):
    • This loop runs from i = 0 to i = 8 (inclusive). It controls the number of rows to be printed.
  • Inner Loop (for j in range(1, i)):
    • For each value of i, this loop runs from j = 1 to j < i. It prints numbers from 1 to i-1.
  • Print Statements:
    • print(j, end=" "): Prints the value of j followed by a space, without moving to a new line.
    • print(): Moves to the next line after completing the inner loop.
Output of the First Part
  • When i = 0: The inner loop does not execute because the range is empty.
  • When i = 1: The inner loop does not execute because the range is empty.
  • When i = 2: The inner loop runs once, printing 1.
  • When i = 3: The inner loop runs twice, printing 1 2.
  • This pattern continues until i = 8, where the inner loop prints 1 2 3 4 5 6 7.

Resulting output for the first part:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 

Second Part: Descending Pattern

for i in range(rows + 1, 0, -1):
    for j in range(1, i):
        print(j, end=" ")
    print()
  • Outer Loop (for i in range(rows + 1, 0, -1)):
    • This loop runs from i = 9 to i = 1 (exclusive), decrementing by 1 each time. It controls the number of rows to be printed in descending order.
  • Inner Loop (for j in range(1, i)):
    • For each value of i, this loop runs from j = 1 to j < i. It prints numbers from 1 to i-1.
  • Print Statements:
    • print(j, end=" "): Prints the value of j followed by a space, without moving to a new line.
    • print(): Moves to the next line after completing the inner loop.
Output of the Second Part
  • When i = 9: The inner loop runs eight times, printing 1 2 3 4 5 6 7 8.
  • When i = 8: The inner loop runs seven times, printing 1 2 3 4 5 6 7.
  • This pattern continues until i = 2, where the inner loop prints 1.

Resulting output for the second part:

1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1