-1

The printing output I'm getting contains the list that I want, but also the word None for some reason. I have a function defined as factors and my main function that is trying to print the factors of a specified number. Like I said, my output is:

[1, 17]
None

This is what my current code looks like and everything is indented, but stack overflow wont let me copy it over cleanly:

def factors(myNumber):
    fact = []
    for i in range(1, myNumber + 1):
        if myNumber % i == 0:
            fact.append(i)
    print(fact)

def main():
    print(factors(17))

if __name__ == "__main__":
    main()
aaossa
  • 3,763
  • 2
  • 21
  • 34
IcyG
  • 19
  • 4
  • 1
    That's because you `print` the output of `factors(17)`, but that functions does not `return` any value, only prints `fact`. You may want to use `return fact` at the end of your `factors` function. – aaossa Feb 15 '22 at 14:48
  • four space before the code indent it, there is also button in the editor – Caridorc Feb 15 '22 at 14:48

3 Answers3

0

Your factors function returns None, and you are printing it, this is why

olirwin
  • 545
  • 5
  • 21
0

Welcome @IcyG. The output you're seeing happens because you print the output of factors(17), but that functions does not return any value, only prints fact. When you do not include a return statement in a function, it returns None, which is why your second output is a None. You may want to use return fact at the end of your factors function:

def factors(myNumber):
    fact = []
    for i in range(1, myNumber + 1):
        if myNumber % i == 0:
            fact.append(i)
    return fact

def main():
    result = factors(17)  # Added to explicitly show that this returns a value
    print(result)

if __name__ == "__main__":
    main()
aaossa
  • 3,763
  • 2
  • 21
  • 34
  • So return allows me to return values to my predefined list which makes printing possible through a different function? – IcyG Feb 15 '22 at 14:56
  • The `return` statement defines the value that your function will return, exactly. That's why you can pass the value calculated inside `factors` to another function (`main`) . – aaossa Feb 15 '22 at 14:57
0

As others have already explained, your first function returns None (which is the default return value, if a value is not provided). The following code is equivalent to yours and hopefully makes it more clear:

def factors(myNumber):
    fact = []
    for i in range(1, myNumber + 1):
        if myNumber % i == 0:
            fact.append(i)
    print(fact)
    return None

def main():
    result = factors(17)
    print(result)

if __name__ == "__main__":
    main()
jbb
  • 76
  • 3