0

so I am attempting to write a function that returns factors of a given number. when I use the print function my code give the correct output when I use the return function it outputs 1 for ever input.

Here is my code:

def getFactors(x):
    """Returns a list of factors of the given number x.
    Basically, finds the numbers between 1 and the given integer that divide the number evenly.

    For example:
    - If we call getFactors(2), we'll get [1, 2] in return
    - If we call getFactors(12), we'll get [1, 2, 3, 4, 6, 12] in return
    """
    
    # your code here
 
    for i in range(1 , x + 1):
        if x % i == 0:
            return(i)
x = int(input("please enter and integer: "))

getFactors(x)
serge
  • 1
  • 3
  • Because `return` returns from the function. Either use `yield`, or collect the results in a list and then return that, after the loop. In both cases, don't forget to `print` the results outside of the function. – tobias_k Sep 15 '22 at 16:21

1 Answers1

0

A function only returns once. Once it returns it stops running. So your for loop starts up, hits the return line, returns i, and ends. Since you need to return a list of items, then you should append i to a list inside that for loop and then return the whole list. You even mention this functionality in your comment "Returns a list of factors" but didn't implement it.

Something like:

def getFactors(x):
    """Returns a list of factors of the given number x.
    Basically, finds the numbers between 1 and the given integer that divide the number evenly.

    For example:
    - If we call getFactors(2), we'll get [1, 2] in return
    - If we call getFactors(12), we'll get [1, 2, 3, 4, 6, 12] in return
    """
    
    # your code here
    list_to_return=[]
    for i in range(1 , x + 1):
        if x % i == 0:
            list_to_return.append(i)

    return list_to_return

x = int(input("please enter and integer: "))

factors = getFactors(x)
print(factors)
JNevill
  • 46,980
  • 4
  • 38
  • 63
  • No facepalm necessary. This stuff isn't obvious until you've run face first into it a few times. You may find it fun that you can that you can use list comprehension to replace the entire function with just `print([i for i in range(1, x + 1) if x % i == 0])`. Python is a fun language. – JNevill Sep 15 '22 at 16:45
  • Thank you for that I'm still running into the issue of my print function not returning x def factor(inp): for i in range(2 , inp+ 1 ): if inp % i ==0: x.append(i) return (x) x = [] inp = int(input("enter int: ")) factor(inp) print (factor) – serge Sep 15 '22 at 18:00
  • it's likely returning. What you have to do is "Catch" the output of the function into a variable. So `fact = factor(inp)` and then print that variable `print(fact)`. Or if you want to skip straight to printing (and not capture the return into a variable) `print(factor(inp))` – JNevill Sep 15 '22 at 18:05
  • Ooooo thank you it works now ^_^ – serge Sep 15 '22 at 18:09