我正在使用 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)
现在,这个函数将一个三位数转换成它的字母等效字符串(我没有在这里发布整个代码)。现在,如果像“111”这样的数字是输入,那么“十”的值就是 11。这意味着,“s”的新值现在是“一百一十一”。因此,为了返回此值并防止程序进一步检查“单位”值(此处未包含其代码),我尝试调用“最终”函数,并将“s”作为参数。 “final”函数的作用是返回“s”的值。
但是,使用“111”作为输入,我得到“无”作为输出。我的代码有什么问题?
请您参考如下方法:
虽然它看起来可能是正确的,但实际上您并没有为每个结果正确地返回一些东西。
尽管 111 在最后满足条件(111/10 == 11,if ten == 11),但您没有实际上为它返回一个值。
要解决此问题,您需要执行以下操作:
return final(s) # If you don't return it here, you are just throwing it away.
为那个分支返回一些东西。虽然此时你正在调用 final 返回一个值,但它在更深的范围内(它只会 return 给调用者)。要从整个函数返回,如果有意义的话,您需要“返回返回值”。
另外,你得到None的原因是因为当没有返回值时,它相当于返回None,所以这是你的输出。
