Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

AdvancedPhase 3 - Level 4: String-based RecursionExample 7 of 10
print-characters-recursively.py
1def print_chars(s, index=0):
2 # Base case
3 if index >= len(s):
4 return
5
6 # Print current character
7 print(s[index])
8 # Recurse
9 print_chars(s, index + 1)
10
11# Test
12text = 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. 1

    Return when index reaches the string length.

  2. 2

    Print s[index] on its own line.

  3. 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.