Editor

Reverse a String Recursively

Intermediate · Write the code · from Python Recursion: How It Works, When to Use It, and Examples

From the lesson: Python Recursion: How It Works, When to Use It, and Examples

Imagine a set of Russian nesting dolls. You open the biggest one and find a smaller one inside. Open that, and there's an even smaller one. You keep opening until you reach the tiniest doll that doesn't open - that's the end.

Read the lesson

Write a recursive function called reverse that takes a string and returns it reversed.

For example: reverse("hello") should return "olleh".

Hint: the last character plus the reverse of everything except the last character.

Print the results of reverse("hello") and reverse("Python") on separate lines.

def reverse(s):
# Your code here
pass
print(reverse("hello"))
print(reverse("Python"))

More Recursion exercises

All Python exercises · 50 practice problems · Functions quiz