dimanche 19 juillet 2020

Summing Divisors with While Loop and If Statement

Beginner here. I tried to sum all divisors of a number but the number itself. I wrote a code without using "elif".

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

while divisor < n:
    if n == 0:
        return 0
    else:
        n % divisor == 0
        sum += divisor
        divisor += 1

return sum

print(sum_divisors(0))
# 0
print(sum_divisors(3))  # Should sum of 1
# 1
print(sum_divisors(36))  # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102))  # Should be sum of 2+3+6+17+34+51
# 114

I got the answers 0, 1, 630 and 5151. Then, I rewrote the code by using elif. Got the right answers.

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

while divisor < n:
    if n == 0:
        return 0
    elif n % divisor == 0:
        sum += divisor
        divisor += 1
    else:
        divisor += 1

return sum

print(sum_divisors(0))
print(sum_divisors(3))
print(sum_divisors(36))
print(sum_divisors(102))

There are somethings wrong in the first attempt, I feel it but I can't explain it. Is it related to order of operations? Can someone explain what's going on in the execution of first code?

Aucun commentaire:

Enregistrer un commentaire