pythonfactorization

go through each number between 1 and the number input until it finds a factor and adds it to a list


def factorList(num):
    listOfFactors = []
    for i in range <= num:
        if num / i == 0:
            listOfFactors.append(i)
    print(listOfFactors)  
factorList(36)      

I want the function to go through each number between 1 and the number input until it finds a factor and adds it to a list


Solution

  • range() is a function (it needs parens), and it starts at zero, rather than 1...

    You seem to have tried to combine range with a while loop logic, like so

    i = 1
    while i <= num:
      # if ... append ... 
      i += 1
    

    But you can do the same with list-comprehension

    def factorList(num):
        return [i for i in range(1, num+1) if num % i == 0]
    
    print(factorList(36))
    

    Output

    [1, 2, 3, 4, 6, 9, 12, 18, 36]
    

    side-note: For factorization, you only need to loop up to the square-root of the number.