7.reverse help


#1



hello, I just started to learn python for my uni and took this course to help me improve so,

7.reverse 15.Practice Makes Perfect

I can't figure out why my code isnt working any explanation would benefit me a lot.
Oops, try again. Your function fails on reverse("Python!"). It returns "" when it should return "!nohtyP".

I expected to get it right thought.
Thanks in advance!


def reverse(text):
    txet = ''
    for c in range(len(text) -1, 0):
      txet = text[c] + txet
    return txet.


#2

to see what is actually happening, add a function call:

print reverse("Python!")

oops, nothing seemed to have happened. And why is that? Because of this line:

for c in range(len(text) -1, 0):

go from 6 till 0. Well, 6 is already greater then zero, so this for loop will never execute, you might want to pass in a 3rd argument, to indicate your loop should be taking steps of -1:

for c in range(len(text) -1, 0,-1):

you might also want to change the second argument to -1, currently 0 (your first letter) is not included in the loop.

This should help you getting closer to your goal, if you need further help, post an updated version of your code, let me know you need further help, but i highly recommend to try again first. Maybe include some print statements inside the for loop, so you can actually see what is happening?


#3

def reverse(text):
txet = ''
for c in range(len(text) -1, 0, -1):
txet += text[c]
return txet
with this code the first letter of the word isnt appearing in the return, so I changed the second argument with -1 as you said and it worked.
Thank you for your fast reply and help
P.S I thought that the step part on the loop wasnt necessary and python would do this in automode, like it can read that I was starting in the end and moving to start if that even makes sense


#4

the second argument of your for loop is still 0, which means numbers greater then zero, you also need zero, since this contains your first letter P

I already mentioned it in my first answer


#5

I somehow manage to send the reply before it was ready and I cant even write the code with indentations, sorry Im only new here :slight_smile:


#6

actually, zero is not included, a for loop to me looks like this:

for(i = len(text); i > 0; i--)

i-- is short for i -= 1, which is short for i = i - 1. I think python uses something like this, under the hood when you use range(), which explains why 0 wasn't included, if you had more control over the loop, you could have changed this behaviour (use >= instead of >, so you need to change it to -1. Using range is easier, but it gives you less control over the loop.

Good to hear you have the issue resolved. If you want to make your code show on the forum, read this help topic: