0

I have a function to remove punctuation from the end of a word

def clean(word):
    if word[-1].isalpha():
        return word.lower()
    else:
        word = word[:-1]
        clean(word)

If I run for example, print(clean('foo!!!')) the function prints None. However if I change return to print in the function:

def clean(word):
    if word[-1].isalpha():
        print(word.lower())
    else:
        word = word[:-1]
        clean(word)

Then the function prints foo. Why the difference in this case between return and print?

ggordon
  • 259
  • 1
  • 3
  • 16
  • 4
    Your function isn't truly recursive. The last line in the first example should be `return clean(word)`. It will then work as you expect. – Patrick Haugh Apr 21 '17 at 16:41
  • @juanpa.arrivillaga has a better duplicate for this; it's easier to extract the information you need. – Prune Apr 21 '17 at 16:44
  • Patrick already gave the most exact explanation... I don't think this is quite an exact duplicate of those... – Aaron Apr 21 '17 at 16:45
  • The proper question is why the function returns `None`. And that is answered by looking through all of its code paths. – tdelaney Apr 21 '17 at 16:46
  • @PatrickHaugh I wouldn't say it isn't *truly* recursive, it just doesn't return anything useful, and doesn't have any useful side-effects. – juanpa.arrivillaga Apr 21 '17 at 16:46
  • @juanpa.arrivillaga Maybe it would be more accurate to say that it isn't tail-recursion, which is obviously what they were attempting. – Patrick Haugh Apr 21 '17 at 16:50
  • @PatrickHaugh According to [wikipedia](https://en.wikipedia.org/wiki/Tail_call#Description]), *Note that the tail call doesn't have to appear lexically after all other statements in the source code; it is only important that the calling function return immediately after the tail call, returning the tail call's result if any, since the calling function will never get a chance to do anything after the call if the optimization is performed.* I think it may still be tail-recursive, I'm not sure, and I can't tell because Python doesn't optimize tail calls so I can't do a quick experiment :) – juanpa.arrivillaga Apr 21 '17 at 17:03

1 Answers1

1

change your function so it can make recursive call:

def clean(word):
if word[-1].isalpha():
    return word.lower()
else:
    word = word[:-1]
    return clean(word)
Tango
  • 123
  • 2
  • 12