0

I'm having trouble understand how to fix the below code so the function will print a_string in reverse. I know rev is not defined...just couldn't figure out how to make it work. Any help would be great, thanks.

def reverse(a_string):

  for i in range(len(a_string)-1, -1, -1):
    rev =rev+ a_string[i]
    return rev
reverse("cat")
print(rev)
4
  • Set rev to an empty string before the for loop. Commented Nov 13, 2020 at 3:24
  • I done that but still error says undefined ---> rev="" between def & for? Commented Nov 13, 2020 at 3:28
  • You have to define the variable before you use it. See any tutorial on accumulating results -- in your case, likely covered in a tutorial on string processing. Commented Nov 13, 2020 at 3:29
  • Since your print statement is outside of your function you'll have to define rev outside your funciton as well i think. Commented Nov 13, 2020 at 3:30

2 Answers 2

1

I wonder, why don't you do it this way:

return a_string[::-1]

Unless you wanna do it manually in purpose, of course.

Sign up to request clarification or add additional context in comments.

1 Comment

its on purpose as an exercise problem to understand error defined outside functions
0

In order to define rev so python stores it as a string type: rev = "" So your code could look like this:

def reverse(a_string):
    rev = ""
    for i in range(len(a_string)-1, -1, -1):
        rev += a_string[i]
    return rev
print(reverse("cat"))

For the last line [print(rev)], you cannot print the rev variable since it is stored within the function and is not a global variable. So to print the function output you use: print(reverse("cat")).

1 Comment

ty sir! this helps a lot...still a newbie.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.