-5

Could someone please help me understand why the following function does not print out the reverse of the string? What am I doing wrong?

def myReverse(data):
    for index in range( len(data)-1, -1, -1 ):
        return data[index]
        print( data[index] )

myReverse('blahblah')
  • 5
    `return` **exits the function** there and then; you are returning just the last element at that point. the `print()` is never reached. – Martijn Pieters Sep 26 '16 at 09:02
  • 3
    You're returning in the first loop. It never reaches the print function. – Farhan.K Sep 26 '16 at 09:02
  • 1
    Possible duplicate of [Reverse a string in Python](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) – ElmoVanKielmo Sep 26 '16 at 09:04
  • I see . . Thank you. I used ` yield ` as well, but that does not work either. I removed both and left only the ` print ` statement. It works now. –  Sep 26 '16 at 09:10

3 Answers3

1

When you make a return call within the function, the control comes back to parent (which executed the function) ignoring the code within the scope of function after return. In your case, that is why print is not getting executed by your code.

Move the line containing print before return and move return to outside of the for loop. Your code should work then.

Suggestion: There is simpler way to reverse the string using ::-1. For example:

>>> my_string = 'HELLO'
>>> my_string[::-1]
'OLLEH'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

You are returning before print. So the line print( data[index] ) is never get executed.

Below code wil work just fine.

def myReverse(data):
    for index in range( len(data)-1, -1, -1 ):
        print( data[index] , end = '')

Notice that this is a python3 solution. print in Python2 doesn't work like that.

So, get the same effect in python2 , first import the print from __future__.

from __future__ import print_function

And then, same as above.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
0

Intro: the execution of a for loop will stop once a return statement or break statement is encountered or there is an exception.

You have a return statement which makes the for loop stop (returning control to the caller) as soon as the statement is encountered in the first iteration.

Move the return statement outside the for loop

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139