我是一名新手程序员,在 Codecademy 中使用 Python 偶然发现了一个问题。 我得到一个随机正整数 n,需要隔离数字以将它们相加并将总和添加到变量total
这是到目前为止我的代码,请记住我是新手!:)
def digit_sum(n):
total = 0
while len(str(n)) > 0:
total = total + n%10
n -= n//10
最佳答案
您的代码中存在三个问题:
- 该函数不返回值。在末尾添加
返回总计
。 - 您不应在
len(str(n)) > 0
时继续,因为这始终是正确的:任何转换为字符串的数字都将至少包含一个字符。相反,只需验证n > 0
n
不应通过减法调整,而应通过除法调整:n//= 10
这是更正后的代码:
def digit_sum(n):
total = 0
while n > 0:
total = total + n%10
n //= 10
return total
不是问题,但您可以将 total = Total + n%10
缩短 total += n%10
关于Python对数字,'n'中的数字求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210002/