函数返回'无'

Man*_*edi 1 python

我正在使用Python处理一个问题.以下是我要解释的问题的相关代码:

def no_to_words(n):
    num = str(n)
    s = ""
    if(len(num) == 3):
        hunds = n/100
        ten = n%100
        tens = ten/10
        units = ten%10
        if(n == 100):
            return "one hundred"

        if(hunds == 1):                        
            s = s + "one hundred and"
        elif(hunds == 2):
            s = s + "two hundred and"
        elif(hunds == 3):
            s = s + "three hundred and"
        elif(hunds == 4):
            s = s + "four hundred and"
        elif(hunds == 5):
            s = s + "five hundred and"
        elif(hunds == 6):
            s = s + "six hundred and"
        elif(hunds == 7):
            s = s + "seven hundred and"
        elif(hunds == 8):
            s = s + "eight hundred and"
        else:
            s = s + "nine hundred and"

        def final(t):
            ans = t
            return ans
        if(ten == 11):                         
            s = s + " eleven"
            final(s)

print no_to_words(111)
Run Code Online (Sandbox Code Playgroud)

现在,这个函数将一个三位数字转换成它的字母等效字符串(我没有在这里发布整个代码).现在,如果输入数字为'111',那么'ten'的值将为11.这意味着's'的新值现在将是'一百一十一'.因此,为了返回该值并阻止程序进一步检查"单位"值(此处未包含的代码),我尝试调用'final'函数,并以's'作为参数."最终"函数的作用是返回's'的值.

但是,以'111'作为输入,我得到'无'作为我的输出.我的代码出了什么问题?

Ale*_*ton 7

虽然它看起来可能正确,但实际上并不是return每个结果都适合的东西.

虽然111在最后(111 / 10 == 11,if ten == 11)满足条件,但实际上并没有为它返回值.

要解决此问题,您需要执行以下操作:

return final(s)  # If you don't return it here, you are just throwing it away.
Run Code Online (Sandbox Code Playgroud)

到return那个分支的东西.虽然目前你正在调用final哪个返回一个值,但它在更深的范围内(它只return对调用者而言).要从整体函数返回,如果有意义,则需要"返回返回的值".


另外,你得到的原因None是因为当没有返回值时,它等同于返回None,因此这是你的输出.

  • 我也不明白OP函数final()的目的.它需要一个参数,将它分配给另一个变量,然后返回相同的东西. (2认同)