检查False的正确方法是什么?

编程入门 行业动态 更新时间:2024-10-25 06:23:16
本文介绍了检查False的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

哪个更好? (为什么?)

Which is better? (and why?)

if somevalue == False:

if somevalue is False:

如果somevalue是字符串,您的答案会更改吗?

Does your answer change if somevalue is a string?

推荐答案

它取决于somevalue的含义:如果somevalue可以是任何东西,则可以检查它是否是布尔值和not:

It rather depends on what somevalue can be: if somevalue could be anything you could check that it's a boolean and not:

if isinstance(somevalue, bool) and not somevalue

这不依赖于False是单身人士.如果始终是单身人士,您也可以执行以下操作:

this doesn't rely on False being a singleton. If it always is a singleton you can also do:

if somevalue is False

但是 Python的PEP8声明您不必关心该类,而只需使用:

But PEP8 of Python states you shouldn't care if it about the class and just use:

if not somevalue

这将评估somevalue是否为"falsy".请参阅有关真值测试的Python文档.

this will evaluate if somevalue is "falsy". See Python documentation on Truth value testing.

PEP8状态:

请勿使用==将布尔值与True或False进行比较.

Don't compare boolean values to True or False using == .

并给出以下示例:

Yes: if greeting: No: if greeting == True: Worse: if greeting is True:

根据您的情况将其翻译为:

which translates in your case to:

Yes: if not greeting: No: if greeting == False: Worse: if greeting is False:

请记住,除了空字符串''外,每个字符串都被认为是真实的".

Keep in mind that each string is considered "truthy" except the empty string ''.

更多推荐

检查False的正确方法是什么?

本文发布于:2023-07-17 02:41:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128548.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   方法   False

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!