Print Triangle (Top-Down) Recursively

Print right triangle recursively.

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

Output

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

What's going on

Print row with row stars, then recurse.

Key Concepts:

Print row stars (1, 2, 3, ...)
Recurse with row + 1
Base case when row > n