Print Reverse Triangle Recursively

Print reverse triangle pattern recursively.

IntermediatePhase 3 - Level 3: Pattern RecursionExample 6 of 10
print-reverse-triangle-recursively.py
1def print_stars(n):
2 if n == 0:
3 return
4 print("*", end="")
5 print_stars(n - 1)
6
7def print_reverse_triangle(n, row=1):
8 # Base case
9 if row > n:
10 return
11
12 # Recurse first
13 print_reverse_triangle(n, row + 1)
14 # Print spaces
15 print(" " * (n - row), end="")
16 # Print stars
17 print_stars(row)
18 print()
19
20# Test
21n = int(input("Enter rows: "))
22print_reverse_triangle(n)

Output

Enter rows: 5
    *
   **
  ***
 ****
*****

What's going on

Recurse first, then print with spaces.

Key Concepts:

Recurse before printing
Add spaces for alignment
Creates right-aligned triangle