[Tutor] Question Regarding Quiz Material

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jun 1 10:44:53 EDT 2021


On 01/06/2021 13:21, Nick Yim wrote:

> I am wondering why the numbers - n = 3, n = 36, n 102 - are not included in
> the list of divisors?
> 
> As well, why is the number 1 included as a divisor of 3 and 36, but not as
> a divisor of 102?

I don't see those issues in the code below?


Please post in plain text, otherwise the mail system strips
all indentation as below...

> def sum_divisors(n):
> x = 1
> #trying all the numbers from 1, because you cannot divide by 0

for x in range(1,n+1):

> sum = 0
> #adding to 0
> while n!=0 and x<n:

The for loop would do all that for you.

> #error because the answer does not include the number itself

The for loop would handle that too.

> if n%x == 0:
> sum += x
> x +=1

And the for loop does that too.

> return sum

Or you could do it all with a generator expression:

def sum_divisors(n):
   return sum(x for x in range(1,n+1) if n%x==0)


-- 
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