[英]Simple python function returning None, AND I am using a return statement
I have no idea why this is returning None 我不知道为什么这不返回
def list_union(self,A,B):
A = self.separate(A["fill"])
B = self.separate(B["fill"])
print A
print B
if len(A)==1 and A[0]=="no":
return B.sort()
if len(B)==1 and B[0]=="no":
return ["no"]
Just assume and A and B are being returned as a list type( which it is and it is working fine) 只需假设A和B作为列表类型返回(它确实可以正常工作)
A and B may contain the strings yes or no. A和B可能包含字符串yes或no。 I just don't get why they are returning None.
我只是不明白为什么他们不返回None。
Let me add, I don't care if these two are statements are false because there is more to this program, but I figure whatever issue I am having can be solved by figuring out why this isn't working. 让我补充一点,我不在乎这两个语句是否为假,因为该程序还有更多内容,但是我想出了什么问题可以通过弄清楚为什么它不起作用来解决。
By default a function in Python returns None
. 默认情况下,Python中的函数返回
None
。 In your case, it has two exit points, but they will be reached only if one of the conditions is True
. 在您的情况下,它有两个出口点,但是只有在其中一个条件为
True
,它们才能达到。 Ask yourself, what happens if both conditions are False
? 问问自己,如果两个条件都为
False
怎样? add another return at the end, to handle this case and return an appropriate value (or raise an exception, if it makes sense): 在末尾添加另一个return,以处理这种情况并返回一个适当的值(或抛出一个异常,如果有意义):
return "Unexpected result" # just an example
Also, notice that sort()
does not return a value (it sorts the list in-place), so it'll evaluate to None
, too! 另外注意,
sort()
没有返回值(它排序就地列表),所以它会评估为None
呢! In other words, you should change this line: 换句话说,您应该更改此行:
return B.sort()
Do this instead: 改为这样做:
B.sort()
return B
Or do this, which does return a new sorted list: 或者做到这一点,这并返回一个新的排序列表:
return sorted(B)
B.sort()
doesn't return B, it returns None
! B.sort()
不返回B,它返回None
! (But B is sorted as you wanted) (但是B可以根据需要排序)
You can use sorted(B)
that will return what you want. 您可以使用
sorted(B)
来返回您想要的内容。
Indeed, the built-in sort() method modifies the list in-place. 实际上,内置的sort()方法可就地修改列表。
sorted() built-in function builds a new sorted list. 内置函数sorted()生成一个新的排序列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.