在 Python 的 If 语句中使用布尔值

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

Using a Boolean in an If-Statement in Python

pythonif-statementboolean

提问by Rohan Khajuria

I have some code with an if-statement in it, and one of the conditions is a boolean. However, CodeSkulptor says "Line 36: TypeError: unsupported operand type(s) for BitAnd: 'bool' and 'number'". Please help if you can. This is what that piece of code looks like. (I just changed all the variable names and what the if-statement executes)

我有一些带有 if 语句的代码,其中一个条件是布尔值。但是,CodeSkulptor 说“第 36 行:TypeError:BitAnd 不支持的操作数类型:‘bool’和‘number’”。如果可以的话请帮忙。这就是那段代码的样子。(我只是更改了所有变量名称以及 if 语句执行的内容)

thing1 = True
thing2 = 3

if thing2 == 3 & thing1:
   print "hi"

采纳答案by pradyunsg

You want to use logical and(not the &, which is a bitwise AND operator in Python):

您想使用逻辑and(而不是&,它是 Python 中的按位 AND 运算符):

if thing2 == 3 and thing1:
   print "hi"

Because you have used &, the error has popped up, saying:

因为你用过&,所以弹出错误,说:

TypeError: unsupported operand type(s) for BitAnd: 'bool' and 'number'
                                           ^^^^^^

回答by Blender

&is the bitwise AND operator. You want to use the logical andinstead:

&是按位与运算符。您想改用逻辑and

if thing2 == 3 and thing1:
    print "hi"