Python Code Example: christmas tree pattern

This Python code snippet generates a pattern that involves stars (*) and vertical bars (|). The pattern is a combination of right-aligned stars followed by vertical bars, resembling a right triangle shape.

Code Example

n = 10

for i in range(0, n):
    for j in range(1, n - i):
        print(" ", end="")
    print("*", end="")
    for k in range(0, i):
        print("|", end="")
    for j in range(1, i):
        print("|", end="")
    if i > 0:
        print("*", end="")
    print()

Output

         *
        *|*
       *|||*
      *|||||*
     *|||||||*
    *|||||||||*
   *|||||||||||*
  *|||||||||||||*
 *|||||||||||||||*
*|||||||||||||||||*

Code Explanation

Initial Setup

n = 10
  • A variable n is initialized with the value 10. This determines the height of the pattern.
  • Outer Loop (for i in range(0, n)):
    • This loop runs from i = 0 to i = 9. It controls the rows of the pattern.
  • First Inner Loop (for j in range(1, n - i)):
    • For each value of i, this loop runs from j = 1 to j < n - i. It prints spaces to ensure the star (*) is right-aligned.
  • Print Star (print("*", end="")):
    • After printing the spaces, this statement prints a star (*), staying on the same line.
  • Second Inner Loop (for k in range(0, i)):
    • For each value of i, this loop runs from k = 0 to k < i. It prints vertical bars (|) immediately after the first star.
  • Third Inner Loop (for j in range(1, i)):
    • This loop runs from j = 1 to j < i. It prints additional vertical bars (|) after the ones printed by the second inner loop. This results in i - 1 additional vertical bars.
  • Conditional Print Star (if i > 0: print("*", end="")):
    • If i is greater than 0, an additional star (*) is printed at the end of the vertical bars.
  • New Line (print()):
    • This statement moves the cursor to the next line after completing all prints in the current row.