Print Characters Recursively

Print each character of string recursively.

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

What's going on

Print current character, recurse for next.

Key Concepts:

Base case: index >= len(s)
Print character at index
Recurse with index + 1