python - "while"循环问题

标签 python loops while-loop

我必须以某种方式执行一个函数,当我执行它时,我将能够以如下所示的方式添加一个数字的所有除数。

这让我抓狂,我已经遇到同样的问题大约一个小时了。

def sum_divisors(n):
  # Return the sum of all divisors of n, not including n
  divisor = 1
  while divisor < n:
    if n%divisor==0:
      return divisor
      divisor = divisor + 1
    else:
      divisor = divisor + 1

print(sum_divisors(6)) # Should be 1+2+3=6
print(sum_divisors(12)) # Should be 1+2+3+4+6=16

最佳答案

def sum_divisors(n): 
    sum = 0
    z = 1

    while n > z:
        if n % z == 0:
            sum = sum + z
            z = z + 1
        else:
            z = z + 1
    # Return the sum of all divisors of n, not including n
    return sum

关于python - "while"循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60071100/

相关文章:

python - 如何在一行上一次打印一个字符?

python - 如何在 python 中解析 HTTP 请求(自定义 Web 服务器)

php - PHP在代码错误时

java - 如果用户输入不是整数,并且允许用户提供另一个输入,如何确保引发异常?

使用 while 的 C 程序 - 如果 counter>8 则出现奇怪的计数器错误

python - 将列表列表解压到 pandas 数据帧中的性能

python - 根据 Dataframe 中的项目生成唯一的可能组合

java - 如何修复按重量对包裹进行排序的循环

javascript - 循环浏览页面直到找到特定电影

java - 在 Eclipse 中调试 for 循环的舒适方法