Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

Python function returns None, unclear why

I am pretty new to python and am hitting an issue I cannot explain. I have tried searching through the forum answers here, but what I am finding does not match up with my situation. It feels like I am missing something pretty basic, but I'm not seeing it (obviously...)

This code runs the way I expect:

import string

mults = [1,2,3,4,6,7,9,10,12,15,16,19,21,22,24]

def factor_exp(lst):
    if lst[-1] == 1:
        lst.pop()
        return lst+[1]
    if lst[-1] == 2:
        lst.pop()
        return lst+[1,1]
    else:
        return "Should never get here"

print factor_exp([1])
print factor_exp([2])
print factor_exp([1,2])

This returns:

>>> 
[1]
[1, 1]
[1, 1, 1]

Which is what I want.

I thought using append and extend on the list inside the function would work also. One "append" added near the bottom of the code.

import string

mults = [1,2,3,4,6,7,9,10,12,15,16,19,21,22,24]

def factor_exp(lst):
    if lst[-1] == 1:
        lst.pop()
        return lst+[1]
    if lst[-1] == 2:
        lst.pop()
        return lst.append([1,1])
    else:
        return "Should never get here"


print factor_exp([1])
print factor_exp([2])
print factor_exp([1,2])

But this returns:

>>> 
[1]
None
None

Why are the "None's" appearing? Thanks in advance for any help or insights.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I didn't study your code, but I'd say that it's for this line:

return lst.append([1,1])

list.append() always returns None.

So lst.append([1,1]) will append [1,1] to lst and return None.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...