HELP! : reverse


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/1?curriculum_id=4f89dab3d788890003000096

The error says it returns none instead of !nohtyP when reverse("Python!") is executed

I think it actually works


def reverse(text):
    please=[]
    text = str(text)
    for c in range(len(text)):
        please.append(1)
    for i,a in enumerate(text):
        please[len(text) - i-1]=a
    h=""
    for a in please:
        h+= a
    print str(h)


#2

Try return h instead of print str(h)

Also, here is how I did it in case you want to see a different way

def reverse(text):
    rev_text=""
    for n in range(len(text)-1,-1,-1):
        rev_text+=text[n]
    return rev_text

#3

Awesome! appreciate it


#4

When you code in codecademy's editor, always use return in functions unless its said to print something, and your welcome :slight_smile:


#5

Could you please explain the function of the -1 s added to this?


#6

Well, the range() function works like this

range([start], stop[, step])

start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.

Since we want to reverse the word we start from the last letter hence len(text)-1, the reason for stop=-1 is because indices in list go from 0 and not from 1. So if we want to work with the character on index 0 we need to stop at -1. And the step is -1, meanining count from len(text) backwards with step -1.

Hope this makes it clear


#7

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