简体   繁体   中英

Am getting a Syntax error saying invalid syntax when i combine bitwise and logical operator in an if statement in python

Below is the code, I want to the program to display something after verifying the variable status is between 0 to 20.

status = 12
if (status >= 0 & <= 20):
   print("something")

Yes, this is a syntax error. Both & and and (which is the one you should be using) expect two expressions as operands, and <= 20 is not a valid expression.

if status >= 0 and status <= 20:

However, comparison operators are parsed specially to allow for chaining of comparisons.

0 <= status <= 20

is not parsed as nested expressions like (0 <= status) <= 20

>>> ast.dump(ast.parse('(0 <= status) <= 20'))
"Module(body=[Expr(value=Compare(left=Compare(left=Num(n=0), ops=[LtE()], comparators=[Name(id='status', ctx=Load())]), ops=[LtE()], comparators=[Num(n=20)]))])"

or 0 <= (status <= 20)

>>> ast.dump(ast.parse('0 <= (status <= 20)'))
"Module(body=[Expr(value=Compare(left=Num(n=0), ops=[LtE()], comparators=[Compare(left=Name(id='status', ctx=Load()), ops=[LtE()], comparators=[Num(n=20)])]))])" 

, but as a single expression consisting of two comparison operations.

>>> ast.dump(ast.parse('0 <= status <= 20'))
"Module(body=[Expr(value=Compare(left=Num(n=0), ops=[LtE(), LtE()], comparators=[Name(id='status', ctx=Load()), Num(n=20)]))])"

The semantics are nearly identical to the semantics of 0 <= status and status <= 20 , which the difference being that status is only evaluated once.


In general, x OP1 y OP2 z is equivalent to x OP1 y and y OP2 z , where each of OP1 and OP2 can be one of > , < , == , != , >= , <= , is , is not , in , or not in . Most of the combinations are less readable than an explicit conjunction of tests; stick with "natural-looking" combination like x < y <= z , x < y == z , etc.

Try replacing & with and . In python, there is no && , there is only and . In addition, when doing the and operator, each side of the and should be a valid comparison. In the if statement, the first thing that is compared is status >= 0 , which returns a boolean. However, in the next part of the if statement, you put <= 20 , which wouldn't return anything, as it is not a valid comparison. Each part of the if statement should return a boolean value. The code below should solve your problem.

status = 12
if status >= 0 and status <= 20:
   print("something")

or

status = 12
if 0 <= status <= 20:
   print("something")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM