首页 > 解决方案 > 如何最好地更新while循环以找到数字根?

问题描述

我正在尝试创建一个函数来迭代某个数字的数字并重复查找其数字的总和,直到数字中只剩下一个数字。

我想用一个while循环来做到这一点,但循环永远不会结束。我不明白为什么我的更新行 n_s = str(total) 不起作用

def digital_root(n):
    n_s = str(n)
    
    total = 0
    
    while len(n_s) != 1:
        for digit in n_s:
            total += int(digit)
        n_s = str(total)
    return total

标签: pythonloops

解决方案


您没有重置 的值total,因此使用的是最后一个循环中的值,而不是从 0 开始。

def digital_root(n):
    n_s = str(n)

    while len(n_s) != 1:
        total = 0
        for digit in n_s:
            total += int(digit)
        n_s = str(total)
    return total

推荐阅读