Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to reverse a string - Python Program

Example 1 :

def reverse_string(s): """Reverse a string recursively.""" if len(s) <= 1: return s return reverse_string(s[1:]) + s[0] print(reverse_string("hello"))

Output

 
OUTPUT  :
olleh

Example 2 : Advanced Program

def reverse_string_recursive(s): # Base case: if the string is empty or has one character, it's already reversed. if len(s) <= 1: return s else: # Recursive step: reverse the substring from the second character onwards, # and then append the first character of the original string to the end. return reverse_string_recursive(s[1:]) + s[0] # Example usage: input_string = input("Enter a string : ") reversed_string = reverse_string_recursive(input_string) print(f"Original string: {input_string}") print(f"Reversed string: {reversed_string}") input_string_2 = "Python" reversed_string_2 = reverse_string_recursive(input_string_2) print(f"Original string: {input_string_2}") print(f"Reversed string: {reversed_string_2}")

Output

 
OUTPUT :
Enter a string  : Advanced
Original string: Advanced
Reversed string: decnavdA
Original string: Python
Reversed string: nohtyP