-2

I took a few coding classes in college and am trying to relearn the skills I have lost. The program I am attempting to write takes a string and returns that string backwards: "Nope" becomes "epoN" for example. I was just wondering if you could help me figure out exactly what is wrong in my logic or syntax!

EDIT: Thanks everyone. I fixed the problem by making the variable lengthOfWord = len(string)- 1

ALSO I'm sorry I didn't post my error message. I forgot that rule and will do it in the future. Thanks again!

def ReverseString(string):
    finalWord = ""
    lengthOfWord = len(string)
    while lengthOfWord >= 0:
       finalWord = finalWord + string[lengthOfWord]
       lengthOfWord = lengthOfWord - 1
    else:
        print(finalWord)
    return
Tom Carle
  • 1
  • 1
  • 2
    See https://stackoverflow.com/questions/18686860/reverse-a-string-without-using-reversed-or-1 – Ricardo Aug 06 '17 at 16:42
  • 1
    Python has 0-based indexing. Check you indices. – randomir Aug 06 '17 at 16:42
  • When you have some code that returns an error, you should include the error in your question. Neither your logic or your syntax are wrong, you just have an IndexError because of the indices – Mel Aug 06 '17 at 16:44
  • Please take a look at [mcve]. It's important if you ask for debugging help that you include all relevant details (including desired behaviour and traceback). – MSeifert Aug 06 '17 at 16:48

2 Answers2

0

Try this way :

def ReverseString(string):
  return string[::-1]


print(ReverseString("Rezwan"))

Output :

nawzeR

Or you can try :

def ReverseString(string):
  finalWord = ""
  lengthOfWord = len(string) - 1
  while lengthOfWord >= 0:
    finalWord = finalWord + string[lengthOfWord ]
    lengthOfWord = lengthOfWord - 1
  return finalWord

print(ReverseString("Rezwan")) 
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
-1

The index of list-like object in python is zero based. You use length of a string to get the last element of it is out of range. You can get the last element of a list-like object as follows:

list_like_obj[-1]
list_like_obj[length - 1]

And you can reverse a list-like object use slice, method of that object or built-in function:

list_like_ojb[::-1]
list_like.obj.reverse()
reversed(list_like_obj)
stamaimer
  • 6,227
  • 5
  • 34
  • 55