简体   繁体   English

在 Python function 中返回 boolean 的首选方法是什么?

[英]What is the preferred way of returning a boolean in a Python function?

Is one of these preferred over the other?其中一个是否优于另一个?

1) 1)

def even(num):
    if num % 2 == 0:
        return True
    else:
        return False

2) 2)

def even(num):
    return num % 2 == 0

I prefer #2, but I can see why people might like #1 too.我更喜欢#2,但我明白为什么人们也可能喜欢#1。

There is no definitiv answer, it's just about preference.没有明确的答案,只是关于偏好。

There is also this way:还有这种方式:

def even(num):
    if num % 2 == 0:
        return True
    return False

In general try to be consistent with the coding-style of the rest project.一般尽量与 rest 项目的编码风格保持一致。 But, explicit is better than implicit .但是,显式优于隐式 Imagine that during the comparison an exception occurs... Have you handled the exception on the caller?想象一下,在比较过程中发生了异常……您是否处理了调用方的异常? if not then you might have to handle the exception here, and then return a bool value (probably false).如果不是,那么您可能必须在此处处理异常,然后返回一个布尔值(可能为 false)。

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

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