【问题标题】:Syntax for an If statement using a boolean使用布尔值的 If 语句的语法
【发布时间】:2016-11-20 06:32:24
【问题描述】:

我最近刚刚加入了 python3 HypeTrain。但是我只是想知道如何将 if 语句用于布尔值。示例:

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

另外,我可以像这样切换布尔值吗?

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

【问题讨论】:

  • 你试过看看发生了什么吗?
  • 好吧,我确实声明了一个错误:(
  • "如果 Check6228 == False: UnboundLocalError: 在赋值之前引用了局部变量 'Check6228'"
  • 你可能没有定义你的布尔变量。
  • 赋值使用=运算符,==检查相等

标签: python python-3.x if-statement boolean


【解决方案1】:

您可以随意更改布尔值。至于如果:

if randombool == True:

有效,但您也可以使用:

if randombool:

如果你想测试某事是否为假,你可以使用:

if randombool == False

但你也可以使用:

if not randombool:

【讨论】:

    【解决方案2】:

    我想你也可以使用

    if randombool is True:
    
    elif randombool is False:
    

    我认为您不需要使用等号,除非它是 int 或 float。

    如果我错了,请纠正我

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 2020-07-30
      • 2018-04-17
      • 2012-02-09
      • 2015-12-21
      • 2021-08-03
      • 2013-03-26
      • 2013-05-06
      相关资源
      最近更新 更多