Dan Osmith
Dan Osmith

Reputation: 43

Python for loops output into list

def factors(n):
for i in reversed(range(1, n+1)):
    if n % i ==0:
        print(i)

This code currently outputs the factors of a number in a new line ex. factors(18) outputs 18 9 6 etc.... How can I make it so when I type

print("factors for 18 are:", factors(18))

Returns a list of

factors of 18: [18,9,6,3,2,1]

Without having print(i) in my function.

Upvotes: 1

Views: 50

Answers (1)

cymruu
cymruu

Reputation: 3008

def factors(n):
  ret = [] #Make an empty array to store number factors
  for i in reversed(range(1, n+1)):
    if n % i ==0:
      ret.append(i) #append factors
  return ret #return array of factors

print("Factors of 18", factors(18))

Upvotes: 2

Related Questions