Print Triangle (Top-Down) Recursively
Print a growing triangle with recursive Python row helpers. Students trace output before the next row call and use a separate star function for each width.
1def print_stars(n):2 if n == 0:3 return4 print("*", end="")5 print_stars(n - 1)67def print_triangle(n, row=1):8 # Base case9 if row > n:10 return1112 # Print current row13 print_stars(row)14 print()15 # Recurse for next row16 print_triangle(n, row + 1)1718# Test19n = int(input("Enter rows: "))20print_triangle(n)
Output
Enter rows: 5 * ** *** **** *****
In this one
- Print before a row call
- Increase a row width
- Reuse a star helper
How it works
- 1
Stop when row exceeds n.
- 2
Print row stars and end that line.
- 3
Recurse for row + 1.
Edge cases
What happens for n = 0?
What happens for n = 0?
The first row already exceeds n, so nothing prints.
When is a row printed?
When is a row printed?
Before the recursive call for the next row.
What's going on
row begins at one. If it exceeds n, recursion ends; otherwise print_stars(row) produces that row's stars.
The newline completes the row before the function requests row + 1. Thus three rows contain one, two, then three stars. The call stack stores the active row calls and the temporary star calls, each of which needs its own base case.
What happens for n = 0? The first row already exceeds n, so nothing prints.
When is a row printed? Before the recursive call for the next row.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What width does row three use?
Pick an answer to check it.
Question 2
What happens for n = 0?
Pick an answer to check it.
Questions people ask
What happens for n = 0?
The first row already exceeds n, so nothing prints.
When is a row printed?
Before the recursive call for the next row.
What width does row three use?
Three stars.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum