How to Print Name in Reverse order in Python

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. And it is an interview question.

Python reverse name

For instance, 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.

Python script

Python skills used in this script

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.

Result of python script

Related posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.