Reputation: 21
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)
Upvotes: 0
Views: 87
Reputation: 16
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")).
Upvotes: 0
Reputation: 317
I wonder, why don't you do it this way:
return a_string[::-1]
Unless you wanna do it manually in purpose, of course.
Upvotes: 1