-1

I'm trying to add all the integers in the 'a' variable, but this 'a' variable isn't working as a list nor a string, despite having various different integers in it.

I'm writing a Python program that given a positive integer num, provided by the user, prints the sum of all its divisors. I've already tried to make this 'a' variable a list but the same error happens

import math
num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a) 
for i in (b):
    x = num / i
    if math.floor(x) == x:
            c = list(i)

I've already tried to make this 'a' variable a list but the same error happens: 'int object is not iterable'

2 Answers2

1

list() creates a new list, and its argument must be an iterable (e.g. a tuple, another list, etc.). If you only pass one number, i, it won't work.

I suppose what you want to do is not to create a new list with each loop iteration, but add the i element to an already existing list.
You can achieve it this way:

num = int(input("Num: "))
a = num + 1 # because range excludes the last number
b = range(1, a)
divisors = []  # create a new list where the results will be stored
for i in (b):
    x = num / i
    if math.floor(x) == x:
        divisors.append(i)  # add the number at the end of the list

If you want to sum all the divisors, use:

sum(divisors)

An even more 'Pythonic' (though, admittedly, not necessarily easier to read if you're not used to list comprehensions) way to achieve the same result would be:

num = int(input("Num: "))
divisors_sum = sum(i for i in range(1, num + 1) if num//i == num/i)

I assume you're using Python 3 here. In Python 3, // is floor division, so you don't have to use math.floor. See this post for more details on // vs. /.

natka_m
  • 1,297
  • 17
  • 22
0

You can create an empty list outside of the loop: c = [], and then each time append an element to the list by c.append(i).

Hamed
  • 315
  • 2
  • 13