Hawraa Alsaba
Hawraa Alsaba

Reputation: 15

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.

Upvotes: 0

Views: 62

Answers (3)

Christian Garcia
Christian Garcia

Reputation: 59

Because your reverseString method doesnt have a return value. try removing print in your main method.

Upvotes: 0

AChampion
AChampion

Reputation: 30268

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

Upvotes: 2

Darkmoon Chief
Darkmoon Chief

Reputation: 140

Try this:

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


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

main()

Upvotes: -1

Related Questions