[英]Why am I getting invalid syntax in an 'If else' statement? (Python)
[英]Am getting a Syntax error saying invalid syntax when i combine bitwise and logical operator in an if statement in python
下面是代碼,我想讓程序在驗證變量狀態在 0 到 20 之間后顯示一些東西。
status = 12
if (status >= 0 & <= 20):
print("something")
是的,這是一個語法錯誤。 &
和and
(你應該使用的那個)都期望兩個表達式作為操作數,而<= 20
不是一個有效的表達式。
if status >= 0 and status <= 20:
但是,比較運算符經過特殊解析以允許比較鏈接。
0 <= status <= 20
不被解析為嵌套表達式,如(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)]))])"
或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)])]))])"
, 但作為由兩個比較操作組成的單個表達式。
>>> 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)]))])"
語義幾乎與0 <= status and status <= 20
的語義相同,不同之處在於該status
只評估一次。
通常, x OP1 y OP2 z
等價於x OP1 y and y OP2 z
,其中OP1
和OP2
中的每一個都可以是>
、 <
、 ==
、 !=
、 >=
、 <=
、 is
、 is not
、 in
,或not in
。 大多數組合的可讀性不如明確的測試組合。 堅持“自然”的組合,如x < y <= z
、 x < y == z
等。
嘗試用and
替換&
。 在 python 中,沒有&&
,只有and
。 另外,在做and
運算符時, and
的每一邊都應該是一個有效的比較。 在 if 語句中,首先比較的是status >= 0
,它返回 boolean。 但是,在 if 語句的下一部分中,您輸入了<= 20
,它不會返回任何內容,因為它不是有效的比較。 if 語句的每個部分都應返回 boolean 值。 下面的代碼應該可以解決您的問題。
status = 12
if status >= 0 and status <= 20:
print("something")
或者
status = 12
if 0 <= status <= 20:
print("something")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.