Print Line of N Stars Recursively
Print a line of n stars with a recursive function. Students trace printing before the next call and separate the terminating newline from repeated output.
1def print_stars(n):2 # Base case3 if n == 0:4 return56 # Recursive case7 print("*", end="")8 print_stars(n - 1)910# Test11n = int(input("Enter n: "))12print_stars(n)13print()
Output
Enter n: 5 *****
In this one
- Print without newlines
- Reduce a width recursively
- End output in the caller
How it works
- 1
Return at width zero.
- 2
Print one star and recurse for n - 1.
- 3
After all calls return, print the final newline.
Edge cases
What does n = 0 print?
What does n = 0 print?
Only the caller's final newline.
What happens for negative n?
What happens for negative n?
It moves away from zero and eventually raises RecursionError.
What's going on
print_stars writes one star and calls itself with n - 1. At zero it returns without printing another character.
end empty keeps stars on one line. The caller's final print supplies the newline after all calls return. Each call occupies the call stack, so this simple line is better for understanding recursion than for printing huge widths.
What does n = 0 print? Only the caller's final newline.
What happens for negative n? It moves away from zero and eventually raises RecursionError.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What reduces the remaining width?
Pick an answer to check it.
Question 2
What does n = 0 print?
Pick an answer to check it.
Questions people ask
What does n = 0 print?
Only the caller's final newline.
What happens for negative n?
It moves away from zero and eventually raises RecursionError.
What reduces the remaining width?
n - 1.
๐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