【问题标题】:Returning int as None [duplicate]将int返回为None [重复]
【发布时间】:2020-10-20 14:23:26
【问题描述】:

我在这里返回计数,在 return 语句之前给出 <type 'int'> 但在它返回之后我得到的输出是 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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    只有当if 条件为真时,你的函数才会返回:

     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] 为假,则您的函数不会返回任何内容,这就是它返回 None 类型的原因。在函数体中调用自身时添加return,将equal(arr,count)这一行改为return equal(arr,count)

    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
        return equal(arr,count)
    
    
    a=[10,7,12]
    print(equal(a,0)) # I'm getting output here as **None**enter code here
    

    【讨论】:

      【解决方案2】:

      您的if 子句失败,然后您没有返回任何内容。在这种情况下,python 隐式返回None。添加else 子句以在if 失败时返回一些内容

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-20
        • 2023-01-12
        • 2018-11-29
        • 2020-06-14
        • 1970-01-01
        • 1970-01-01
        • 2022-11-21
        • 2019-08-25
        相关资源
        最近更新 更多