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.RUN CODE SNIPPET
#Python Program to Reverse a Sentence Using Recursion def reverse(string): if len(string) == 0: return string else: return reverse(string[1:]) + string a = str(input("Enter the string to be reversed: ")) print("\n",reverse(a))
Enter the string to be reversed: hsilbuP repoleveD
- At the start, we use
def reverse(string)where the
defkeyword is used to define a function and the
reverse(string)is used to call the function to get the value of
- After that we declare an
ifstatement 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
- In the
elsestatement, it returns the function
reverse(string[1:]) + string, where the function
[1:]is used to take elements 1 to the end of the entered string value and the
stringadds zeros (0) at the beginning of the string until it reaches the specified length.
- Here we give the user the option to enter the values and the input values are scanned using the
inputfunction and are stored in the variable
awith the statement/string
("Enter the string to be reversed: "),we use the
strfunction which converts values to a string form
- In the STDIN section of the code editor the input values are entered.
- Using the
- 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.