Python打印的内容超出了我的需要
为什么下面的代码会打印“None”以及我在没有找到匹配项时告诉它要写的内容Python打印的内容超出了我的需要,python,Python,为什么下面的代码会打印“None”以及我在没有找到匹配项时告诉它要写的内容 def subStringMatchExact(target,key): list=[] for fsi in range (len(target)): if key==target[fsi:fsi+len(key)]: list=list+[fsi,] #return list if list!=[]: return
def subStringMatchExact(target,key):
list=[]
for fsi in range (len(target)):
if key==target[fsi:fsi+len(key)]:
list=list+[fsi,]
#return list
if list!=[]:
return list
else:
print 'no match found'
print subStringMatchExact("banana","x")
让我们看看这个
print subStringMatchExact("banana","x")
subStringMatchExactbanana,x返回什么值?别看它是干什么的。看看它返回了什么。有关函数返回内容的提示,请阅读return语句。都是。如果返回值没有值或没有返回值,则返回None
print对该值有什么作用?因为在每个函数的末尾都有一个隐式返回None。这意味着,当您不返回任何内容时,就像在示例的else块中一样,您的函数也不会返回任何内容。因此,subStringMatchExactbanana,x返回None,这将被打印。想想这里的else子句中发生了什么。在if子句中,函数返回一个值。在else子句中,它返回什么
这就是为什么你会得到你想要的结果。print语句正在打印函数的返回值,无论采用if的哪个分支。如果函数退出时未显式返回值,则返回None。在Python中,如果函数未显式返回值,则隐式返回None。
通过打印subStringMatchExact函数的返回值,即使没有找到匹配项,也会得到大于None的结果,因为else子句不会以return语句结束流 试试这样的方法:
def subStringMatchExact(target,key):
list=[]
for fsi in range (len(target)):
if key==target[fsi:fsi+len(key)]:
list=list+[fsi,]
#return list
return list
这样,您总是返回一个列表,而调用subStringMatchExact的代码可能会担心如何处理空列表,即打印未找到、抛出错误等。使用return'no match found'而不是打印'no match found'
您正在使用print语句打印函数返回的任何内容。因此,在else情况下,您需要在函数中返回而不是打印 因此,正确的代码是:
def subStringMatchExact(target,key):
list=[]
for fsi in range (len(target)):
if key==target[fsi:fsi+len(key)]:
list=list+[fsi,]
#return list
if list!=[]:
return list
else:
return 'no match found'
print subStringMatchExact("banana","x")
大家好,谢谢你的提示!最好先掌握基本知识:再次使用tnxBaba@S.Lott当前位置我相信它是thanx的缩写,thanx本身就是英语单词的缩写:谢谢。这本身就是一种简短的感谢。@John Machin and@JUST MY correct OPINION:你是怎么知道这些事情的?为什么@Baba没有使用真正的英语单词?@S.Lott:这是离题的;你应该在元论坛中提出两个独立的新问题。然而,这里有一些简单的答案:1http://www.internetslang.com/TNX.asp 2.我无法接通@Baba频道;也许你可以。-1答案的最后四行可以简单地用返回列表替换。用返回列表替换最后四行,甚至引发一些错误“找不到匹配项”
def subStringMatchExact(target,key):
list=[]
for fsi in range (len(target)):
if key==target[fsi:fsi+len(key)]:
list=list+[fsi,]
#return list
if list!=[]:
return list
else:
return 'no match found'
print subStringMatchExact("banana","x")