-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
4
  • 2
    See stackoverflow.com/questions/18686860/… Commented Aug 6, 2017 at 16:42
  • 1
    Python has 0-based indexing. Check you indices. Commented Aug 6, 2017 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 Commented Aug 6, 2017 at 16:44
  • Please take a look at minimal reproducible example. It's important if you ask for debugging help that you include all relevant details (including desired behaviour and traceback). Commented Aug 6, 2017 at 16:48

2 Answers 2

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")) 
Sign up to request clarification or add additional context in comments.

Comments

-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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.