what is the correct way to check for False? [duplicate]

本小妞迷上赌 提交于 2019-12-01 01:28:20

问题


Which is better? (and why?)

if somevalue == False:

or

if somevalue is False:

Does your answer change if somevalue is a string?


回答1:


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

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

if somevalue is False

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

if not somevalue

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

PEP8 states:

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

and gives these examples:

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 ''.




回答2:


is is checking whether two objects are literally the same object. == is checking for equality.

If you want to check whether something is false, e.g. zero, opposite of True, do if something == False.

As mentioned in the comments, you can certainly do if not something, it may improve readability quite a bit, but it's the same as if bool(something) == False.

I prefer equality, because, to my mind, True and False should behave just like 1 and 0 in terms of being true or false. For example ("a" == "a") == False evaluates to False just like ("a" == "a") == 0 does.



来源:https://stackoverflow.com/questions/37103705/what-is-the-correct-way-to-check-for-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!