简体   繁体   English

Python函数返回None,不清楚为什么

[英]Python function returns None, unclear why

I am pretty new to python and am hitting an issue I cannot explain. 我是python的新手,遇到了我无法解释的问题。 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. 在此先感谢您的帮助或见解。

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 . list.append()始终返回None

So lst.append([1,1]) will append [1,1] to lst and return None . 所以lst.append([1,1])会将[1,1]附加到lst并返回None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM