7. reverse - Tried two codes but not getting it right


#1

So, I've tried reversing the characters in two ways, but on both trials I've got this error:

Oops, try again. Your function fails on reverse("Python!"). It returns "None" when it should return "!nohtyP".

At first I tried this code:

def reverse(str):
    for l in range(len(str) - 1, 0, -1):
        print str[l]

Then this one:

def reverse(str):
    rev = []
    for l in range(len(str) - 1, 0, -1):
        rev.append(str[l])
    "".join(rev)
    print rev

So, which would be the closest to getting it right and how do I change it to work?


#2

Hi @lodbrok96,

In the second example, you have ...

    print rev

Try ...

    return "".join(rev)

Also reconsider the loop header. You have ...

    for l in range(len(str) - 1, 0, -1):

Recall that the stop value, which you have as 0, is exclusive.


#3

Thank you!
It worked.
My code now is:

def reverse(str):
    rev = []
    for l in range(len(str) - 1, 0 - 1, -1):
        rev.append(str[l])
    return "".join(rev)

However, I don't get why I need a return statement at the end of the code. Do all functions need to end in return?


#4

A function is not required to have a return statement. However, if it does not, it will always return the value None. The reverse function is intended to return the result of reversing the characters in the string passed to it via its parameter, so it needs to have a return statement.


#5

2 posts were split to a new topic: Number of arguments for range function


#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.