[Tutor] Help

Alan Gauld alan.gauld at yahoo.co.uk
Wed Oct 7 17:25:24 EDT 2020


On 07/10/2020 21:16, Gilbert Makgopa wrote:

> def sum_divisors(n):
>   sum = 0
>   div =0
>   # Return the sum of all divisors of n, not including n
>   while (div > 0 and div!=n):
>     sum = sum + div
>     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

Where within your function do you check to see if div is actually a
divisor? In fact your function is severely broken and will always
return None (the default return value of a Python function). If
you are getting other results you must be running different
code to what you posted.

Things wrong:
1) You start with div=0 then immediately check if div > 0 which
it isn't.
2) You never modify div or n so the while loop always gives
the same result.
3) You never check if div is actually a diviror of n before
adding it to sum.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list