Here’s a python program that prints the name (entered from terminal) in reverse order. With the help of for loop, range, length, and string operators ( index and slicing) you can achieve it. This is a useful interview question too.
Suppose, your name is ‘veera venkata krishana’. This program reverses it and writes as ‘anahsirk ataknev areev’.
This program takes input from the user. As you execute this Python script, you can see the input name prints in reverse order.
Python skills used in this script
- The range() function. This function uses three arguments – the from number, increment, last element index. You know that like tuple, string is immutable. You can’t change the elements. You need either index (starts with ‘0’) or slicing operator(:) to work with strings.
- The -1 says last element
- The len() function gets length of the string
- The for loop reads all the elements from input string. In this case it is your name.
Here the print(n[::-1]), prints from the last character to the beginning character. So you can see the output in reverse order.
print(n[:-1]) –> pytho (this is output)
print(n[::-1]) –> nohtyp (this is output)
So finally, the output of the main script, the entered string displays in reverse order.
So both the outputs are the same.