Number Patterns Recursively
Generate increasing number rows with recursive helpers. Students separate a row-size function from a per-row number function and trace each helper's boundary.
1def print_numbers(n, current=1):2 # Base case3 if current > n:4 return56 # Print current number7 print(current, end="")8 # Recurse9 print_numbers(n, current + 1)1011def print_pattern(n, row=1):12 # Base case13 if row > n:14 return1516 # Print row17 print_numbers(row)18 print()19 # Recurse20 print_pattern(n, row + 1)2122# Test23n = int(input("Enter rows: "))24print_pattern(n)
Output
Enter rows: 4 1 12 123 1234
In this one
- Separate row and value recursion
- Restart a current argument
- Bound both helpers
How it works
- 1
Choose the next row width in print_pattern.
- 2
Print one through that width with print_numbers.
- 3
End the line and request the next row.
Edge cases
What if n = 0?
What if n = 0?
No rows print.
Does numbering continue across rows?
Does numbering continue across rows?
No. The default current value restarts at one.
What's going on
print_pattern chooses the row width. print_numbers starts at one and prints successive current values until current exceeds that width.
Each row ends before the next row is requested, giving 1, 12, 123 for three rows. Starting current at one for every helper call restarts numbering. Both helpers use the call stack and need their stopping comparisons.
What if n = 0? No rows print.
Does numbering continue across rows? No. The default current value restarts at one.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does print_numbers(row) control?
Pick an answer to check it.
Question 2
What if n = 0?
Pick an answer to check it.
Questions people ask
What if n = 0?
No rows print.
Does numbering continue across rows?
No. The default current value restarts at one.
What does print_numbers(row) control?
Values from one through the current row.
๐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