Python 使用布尔值的 If 语句的语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38423360/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:47:17  来源:igfitidea点击:

Syntax for an If statement using a boolean

pythonpython-3.xif-statementboolean

提问by Lucidity

I just recently joined the python3 HypeTrain. However I just wondered how you can use an if statement onto a boolean. Example:

我最近才加入了 python3 HypeTrain。但是我只是想知道如何在布尔值上使用 if 语句。例子:

RandomBool = True
# and now how can I check this in an if statement? Like the following:
if RandomBool == True:
    #DoYourThing

And also, can I just switch the value of a boolean like this?

而且,我可以像这样切换布尔值吗?

RandomBool1 == True   #Boolean states True
if #AnyThing:
    RandomBool1 = False   #Boolean states False from now on?

回答by Mathime

You can change the value of a bool all you want. As for an if:

您可以随心所欲地更改 bool 的值。至于如果:

if randombool == True:

works, but you can also use:

有效,但您也可以使用:

if randombool:

If you want to test whether something is false you can use:

如果你想测试某些东西是否是假的,你可以使用:

if randombool == False

but you can also use:

但你也可以使用:

if not randombool: