1

I am trying to return an array of a number's divisors. If the number is prime I want to return the string, '(integer) is prime'. Instead of returning this string my function returns an empty array.

Code:

def divisors(num):
    i = 2
    array = []
    while i < num:
        if num % i == 0:
            array.append(i)
        i += 1
    print(array)
    if len(array) > 0:
        return array
    else:
        prime = '%i is prime' %num
        return prime

divisors(3)

Thank you for the help!

1
  • 1
    no it doesn't? repl.it/repls/BurlywoodJumboRectangle (presumably you are looking at the console output, where you print the empty array, but you're not doing anything wth the result of the function) Commented Apr 18, 2020 at 21:47

2 Answers 2

2

What you are seeing is the empty array that you print when your function executes. Your function is correctly returning the string because 3 is prime, but you just haven't assigned the return value of the function to any variable. This should accomplish what you want.

def divisors(num):
    i = 2
    array = []
    while i < num:
        if num % i == 0:
            array.append(i)
        i += 1
    # print(array)
    if len(array) > 0:
        return array
    else:
        prime = '%i is prime' %num
        return prime

value = divisors(3)
print(value)

Output:

'3 is prime'
Sign up to request clarification or add additional context in comments.

Comments

0

Your function does returns the string, the empty array you see is a result of the print(array) statement in the middle of your code, which I assume you added for debugging. Consider removing it.

Use print(divisors(3)) to actually show the resulting string (otherwise it wouldn't show, as it does now).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.