Search code examples
pythonprintingreturn

Python - Return vs Print


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?


Solution

  • 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)