Python 如果 var == False
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16513573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if var == False
提问by Phedg1
In python you can write an if statement as follows
在python中你可以写一个if语句如下
var = True
if var:
print 'I\'m here'
is there any way to do the opposite without the ==, eg
有没有什么方法可以在没有 == 的情况下做相反的事情,例如
var = False
if !var:
print 'learnt stuff'
采纳答案by Tamil Selvan C
Use not
用 not
var = False
if not var:
print 'learnt stuff'
回答by jwodder
var = False
if not var: print 'learnt stuff'
回答by stonesam92
Python uses notinstead of !for negation.
Python 使用not而不是!用于否定。
Try
尝试
if not var:
print "learnt stuff"
instead
反而
回答by Cambium
I think what you are looking for is the 'not' operator?
我认为您正在寻找的是“非”运算符?
if not var
Reference page: http://www.tutorialspoint.com/python/logical_operators_example.htm
参考页面:http: //www.tutorialspoint.com/python/logical_operators_example.htm
回答by colidyre
Since Python evaluates also the data type NoneTypeas Falseduring the check, a more precise answer is:
因为Python还评估的数据类型NoneType作为False在检查过程中,更精确的答案是:
var = False
if var is False:
print('learnt stuff')
This prevents potentially unwanted behaviour such as:
这可以防止潜在的有害行为,例如:
var = [] # or None
if not var:
print('learnt stuff') # is printed what may or may not be wanted
But if you want to check all cases where varwill be evaluated to False, then doing it by using logical notkeyword is the right thing to do.
但是,如果您想检查var将评估为 的所有情况False,那么使用 logicalnot关键字来执行此操作是正确的做法。

