Write a Recursive Function to Print a String Backwards in Python

Given a string as input to the Python program you have to write a Python function that calls itself recursively and prints the character of a given string from the end.  again calls itself by removing the ending character of a given string.


Let's use a try and exception block with the  recursion.

 

 

Write a Recursive Function to Print a String Backwards in Python

 



Write a Recursive Function to Print a String Backwards in Python

Let's define a function named back() and pass the swing type as an input argument to the function.  Let's directly use a try block and try to print the ending character of a given string with the  empty string as a side character.  also call the  save function recursively by removing/  trimming the last character of a given string.


In the except block try to catch the index error,  if the string has reached the starting point then you will get the index error then return 0 as a return value of the  function.

Return 0 will recursively return to the calling function that is itself,  and then to the calling function in the main.

def back(text):
   try:
       print(text[-1], end="")
       return back(text[:-1])
   except IndexError:
       return 0






In the main  program, take a variable named as data and it is a string variable that asks a user to enter a string.  Once the user enters a string, call the recursive function named as back()  and print the string in the reverse order.

data = input("Enter a String : ")
back(data)





Python code
====================

def back(text):
   try:
       print(text[-1], end="")
       return back(text[:-1])
   except IndexError:
       return 0


data = input("Enter a String : ")
back(data)




Output
=======================

> python main.py
Enter a String :  python code
edoc nohtyp




Output
=======================

> python main.py
Enter a String : hello
olleh




Output
=======================

> python main.py
Enter a String : Write a Recursive Function to Print a String Backwards in Python
nohtyP ni sdrawkcaB gnirtS a tnirP ot noitcnuF evisruceR a etirW




Conclusion
===================

Execute the above program by providing the random string values and note down the result. Comment down below if you have suggestions to improve the above code.





Post a Comment

0 Comments