Python Program to Reverse a Sentence Using Recursion

In this python tutorial, you will learn how to Reverse a Sentence Using Recursion with the built in functions and operators of the python programming language.

How to Reverse a Sentence Using Recursion?

Let’s take a look at the source code,  here the values are given as input by the user in the code, the built in functions and operators carry out the function.

#Python Program to Reverse a Sentence Using Recursion
def reverse(string):
    if len(string) == 0:
        return string
        return reverse(string[1:]) + string[0]
a = str(input("Enter the string to be reversed: "))


Developer Publish


Enter the string to be reversed: 
hsilbuP repoleveD
  1. At the start, we use def reverse(string) where the def keyword is used to define a function and the reverse(string)is used to call the function to get the value of  string.
  2. After that we declare an if statement with the condition len(string) == 0, where if the condition is true, it returns the value of the string, if the condition is not true, it moves to the else statement.
  3. In the else statement, it returns the function reverse(string[1:]) + string[0] , where the function [1:] is used to take elements 1 to the end of the entered string value and the string[0] adds zeros (0) at the beginning of the string until it reaches the specified length.
  4. Here we give the user the option to enter the values and the input values are scanned using the input function and are stored in the variable a  with the statement/string ("Enter the string to be reversed: "),we use the str function which converts values to a string form
  5. In the STDIN section of the code editor the input values are entered.
  6. Using the print function we display the final value of the String which is stored in the variable a.


  • Reverse() is an inbuilt method in the Python that reverses objects of the List in place.
  • The input() function allows a user to insert a value into a program, it returns a string value.
  • The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
  • The colon : at the end of the if and else statement tells Python that the next line of code should only be run if the condition is true.
  • The statement for the input function are enclosed in single quotes and parenthesis.
  • The \n in the code indicates a new line or the end of a statement line or a string.
  • The print statement/string to be displayed in enclosed in double quotes.