简体   繁体   English

Python def function 返回 在所有情况下都没有

[英]Python def function return None in all cases

def leap(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
    else:
        return False


print(leap(1992))

It always returns the none value but I want to print the bool in result它总是返回none值,但我想在结果中打印bool

Your code你的代码

def leap(year):
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
    else:
        return False


print(leap(1992))

Let's break it down for 1992.让我们把它分解为 1992 年。

  1. year = 1992.年 = 1992。

    1992 % 4 = 0. True. 1992 % 4 = 0。是的。 The code moves to next if statement.代码移至下一个 if 语句。

    1992 % 100 = 92(False). 1992 % 100 = 92(错误)。 so your codes halts at this point and exits from the function.所以你的代码此时停止并从 function 退出。 Hence the None output for 1992 since you haven't added any logic to return false here.因此1992None output 因为您没有添加任何逻辑来在此处返回 false。

A simple approach to avoid the None output would be.避免None output 的简单方法是。

def leap(year):
    if year % 4 == 0 and year % 100 == 0 and year % 400 == 0:
        return True
    else:
        return False


print(leap(1992))

Try this:尝试这个:

def leap(year):
    return (year%4==0 and year%100!=0 or year%400==0)

This is equivalent to this with if-else format:这等效于 if-else 格式:

def leap(year):
    if year%4 == 0:
        if year%100 == 0:
            if year%400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

You missed out the else parts, and for those cases, the function won't return any boolean value and return None .您错过了其他部分,对于这些情况, function 不会返回任何 boolean 值并返回None The above function can be simplified with removing the return False conditions inside else parts and add one at the last of the function.上面的 function 可以通过删除 else 部分中的 return False 条件并在 function 的最后添加一个来简化。

def leap(year):
    if year%4 == 0:
        if year%100 == 0:
            if year%400 == 0:
                return True
        else:
            return True
    return False

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

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