Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Recursion Functions

Recursive function to find length of a string - Python Program

Example 1 :

def string_length(s): """Find length of a string recursively.""" if s == "": return 0 return 1 + string_length(s[1:]) print(string_length("Python"))

Output

 
OUTPUT  :
6

Example 2 : Advanced Program

def recursive_string_length(s): """ Calculates the length of a string using recursion. Args: s: The input string. Returns: The length of the string. """ # Base case: If the string is empty, its length is 0. if s == "": return 0 # Recursive step: Add 1 (for the current character) and # recursively call the function for the rest of the string. else: return 1 + recursive_string_length(s[1:]) # Example usage: my_string = input("Enter a String : ") length = recursive_string_length(my_string) print(f"The length of '{my_string}' is: {length}") another_string = "" length_empty = recursive_string_length(another_string) print(f"The length of '{another_string}' is: {length_empty}")

Output

 
OUTPUT  :
Enter a String  : Advanced Python
The length of 'Advanced Python' is: 15
The length of '' is: 0