Python for循环输出到列表

时间:2018-09-22 21:22:03

标签: python list

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

此代码当前在换行符ex中输出数字的因数。 factor(18)输出18 9 6等。...输入

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

返回

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

我的函数中没有print(i)。

1 个答案:

答案 0 :(得分:2)

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