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[0] a = str(input("Enter the string to be reversed: ")) print("\n",reverse(a))
INPUT:
Developer Publish
OUTPUT:
Enter the string to be reversed: hsilbuP repoleveD
- At the start, we use
def reverse(string)
where thedef
keyword is used to define a function and thereverse(string)
is used to call the function to get the value ofstring
. - After that we declare an
if
statement with the conditionlen(string) == 0
, where if the condition is true, it returns the value of thestring
, if the condition is not true, it moves to theelse
statement. - In the
else
statement, it returns the functionreverse(string[1:]) + string[0]
, where the function[1:]
is used to take elements 1 to the end of the entered string value and thestring[0]
adds 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
input
function and are stored in the variablea
with the statement/string("Enter the string to be reversed: ")
,we use thestr
function which converts values to a string form - In the STDIN section of the code editor the input values are entered.
- Using the
print
function we display the final value of the String which is stored in the variablea
.
NOTE:
- 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.