Python 将int返回为None
我在这里返回count,它在return语句给出Python 将int返回为None,python,python-3.x,Python,Python 3.x,我在这里返回count,它在return语句给出之前,但是在它返回之后,我得到的输出是None def equal(arr,count): arr = sorted(arr) if arr[0]==arr[-1]: print(count) # the answer I’m getting is correct so I don’t #think there’s a problem with rest of the code r
之前,但是在它返回之后,我得到的输出是None
def equal(arr,count):
arr = sorted(arr)
if arr[0]==arr[-1]:
print(count) # the answer I’m getting is correct so I don’t
#think there’s a problem with rest of the code
return count
if (arr[-1]-arr[0])>=5:
diff=5
elif(arr[-1]-arr[0])>=2:
diff=2
else:
diff=1
for i in range(len(arr)-1):
arr[i]+=diff
count+=1
equal(arr,count)
a=[10,7,12]
print(equal(a,0)) # I'm getting output here as **None**enter code here
仅当
if
条件为true时,函数才会返回,如第行所示:
if arr[0]==arr[-1]:
print(count) # the answer I’m getting is correct so I don’t
#think there’s a problem with rest of the code
return count
但是如果条件,arr[0]==arr[-1]
为false,则函数不会返回任何内容,这就是它返回None
类型的原因。当函数在主体中调用自身时,添加一个return
,行equal(arr,count)
更改为return equal(arr,count)
仅当
if
条件为true时,函数才会返回,如第行所示:
if arr[0]==arr[-1]:
print(count) # the answer I’m getting is correct so I don’t
#think there’s a problem with rest of the code
return count
但是如果条件,arr[0]==arr[-1]
为false,则函数不会返回任何内容,这就是它返回None
类型的原因。当函数在主体中调用自身时,添加一个return
,行equal(arr,count)
更改为return equal(arr,count)
如果子句失败,则不会返回任何内容。在这种情况下,python隐式返回
None
。添加一个else
子句以返回某些内容,以防if
失败如果您的if
子句失败,则您不会返回任何内容。在这种情况下,python隐式返回None
。添加一个else
子句,以在if
失败时返回某些内容