Print Characters Recursively
Print text one character per line with Python recursion. Students advance an index, keep the original string unchanged, and stop before indexing past the end.
1def print_chars(s, index=0):2 # Base case3 if index >= len(s):4 return56 # Print current character7 print(s[index])8 # Recurse9 print_chars(s, index + 1)1011# Test12text = input("Enter a string: ")13print_chars(text)
Output
Enter a string: Hello H e l l o
In this one
- Print an indexed character
- Check bounds before access
- Recurse without slicing
How it works
- 1
Return when index reaches the string length.
- 2
Print s[index] on its own line.
- 3
Request index + 1 with the same string.
Edge cases
What happens for empty text?
What happens for empty text?
No character lines print.
Does the function return a new string?
Does the function return a new string?
No. Its purpose is printing, not rebuilding text.
What's going on
The function checks the index before reading s[index]. It then prints that character and requests index + 1.
For cat, three print calls produce c, a, and t on separate lines. A space also gets its own line. The base case prevents IndexError, while recursion depth still limits very long inputs because active calls occupy the call stack.
What happens for empty text? No character lines print.
Does the function return a new string? No. Its purpose is printing, not rebuilding text.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why test index first?
Pick an answer to check it.
Question 2
What happens for empty text?
Pick an answer to check it.
Questions people ask
What happens for empty text?
No character lines print.
Does the function return a new string?
No. Its purpose is printing, not rebuilding text.
Why test index first?
To avoid accessing beyond the string.
๐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