python - 如何最好地更新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
解决方案
您没有重置 的值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
推荐阅读
- python - Spacy:如何使用您自己的分隔符创建标记器
- javascript - 使用模拟器启动本机应用程序时出错
- r - R中的if和ifelse,使用了多个元素&嵌套失败
- postgresql - 在 knex.js / Bookshelf.js 中构建复合内连接
- javascript - 在 Fuse react 中配置私有路由时超出最大更新深度错误
- javascript - 使用 webpack 从库中公开变量
- reactjs - 上下文消费者中的 useReducer 在某些位置发生更改后不会更新
- django - 使用更多模型创建视图
- cplex - DoCplex:在热启动中使用变量子集
- kubernetes - 如何使用 Skaffold 转发特权端口