1

这是我遇到的问题,而不是返回 new_word 并将其打印出来,它只是打印“无”

    text = "hey hey hey,hey"
    word = 'hey'

    def censor(text,word):
        new_word = ""
        count = 0
        if word in text:
            latter_count = ((text.index(word))+len(word))
            while count < text.index(word):
                new_word+= text[count]
                count += 1
            for i in range(len(word)):
                new_word += '*'
            while latter_count < len(text) :
                new_word += text[latter_count]
                latter_count += 1

            if word in new_word :
                censor(new_word,word)
            else :
                return new_word
    print censor(text,word)
4

3 回答 3

4

None如果没有 return 语句,则函数返回。

可能在进行递归时,if word in text:是 False,所以没有什么可以返回。您也没有返回递归步骤。你必须返回 censor(new_word,word)

于 2013-07-07T01:12:45.320 回答
2

您不会在if接近尾声的第一个分支中返回。将其更改为

if word in new_word:
    return censor(new_word,word)

如果为 false,您的函数也将返回 None word in text,因此您可能希望else在末尾添加一个以在这种情况下返回空字符串或其他一些默认值。

于 2013-07-07T01:12:27.210 回答
0

如果函数到达末尾而没有遇到“return”语句,则与“return None”相同:

def censor(text,word):
    new_word = ""
    count = 0
    if word in text:
        latter_count = ((text.index(word))+len(word))
        while count < text.index(word):
            new_word+= text[count]
            count += 1
        for i in range(len(word)):
            new_word += '*'
        while latter_count < len(text) :
            new_word += text[latter_count]
            latter_count += 1

        if word in new_word :
            censor(new_word,word)  # probably want to return here
        else :                     # don't need this else if you return in the if branch
            return new_word

    # what do you want to return in this case?
    return None
于 2013-07-07T02:41:06.993 回答