Search code examples
pythonstringloopsreversepython-2.x

A function that reverses a string using a loop


def main():
    print(reverseString("Hello"))

def reverseString(string):
    newString=""
    for i in range(len(string)-1,-1):
        newString+=string[i]
    print newString

main()

I tried running this code but nothing is printed and I don't know what the problem is.


Solution

  • This is missing the step of -1 in the range():

    for i in range(len(string)-1, -1, -1):
    

    Without the step the for loop immediately exits, leaving newstring as ''.

    BTW: you are not returning anything from reverseString() so:

    print(reverseString("Hello"))
    

    Will print None, which I assume is not wanted. You probably want to:

    return newString
    

    in reverseString().