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

Time:09-15

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

CodePudding user response:

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.

CodePudding user response:

range() is a function that returns a sequence of numbers, so you need to call it like a function.

for i in range(num):

See some documentation here: https://www.w3schools.com/python/ref_func_range.asp

  • Related