Python – Return vs Print

Question:

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?

Asked By: ggordon

||

Answers:

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)
Answered By: Tango
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.