簡體   English   中英

我在python代碼中使用OR運算符遇到麻煩

[英]I'm having trouble with the OR operator in my python code

我正在嘗試制作一個具有多個AND,OR和方括號的搜索系統。 在編寫代碼時,我在使用OR時遇到了一些麻煩。 我不知道我的代碼是錯誤的還是計算機是錯誤的,因為有時它給出正確的答案,有時卻給出正確的答案。

sentence = ["A", "B", "C"]
bracket = ["X", "or", "B"]

if "or" in bracket:
   index_of_or = bracket.index("or")
   if bracket[index_of_or -1 ] or bracket[index_of_or +1] in sentence:
      bracket = "True"
      print(bracket)
   else:
      bracket = "False"
      print(bracket)

我正在通過更改括號列表中的元素來檢查代碼。 我將方bracket=['X', 'or', 'Z']放入,輸出為True。

為什么會這樣呢?

您需要分隔條件語句。 你不能這樣做if x or y == 7 : ... ,你必須做if x == 7 or y == 7

考慮到這一點,請更改代碼的相應行以讀取

if bracket[index_of_or -1 ] in sentence or bracket[index_of_or + 1] in sentence:
sentence = ["A", "B", "C"]
bracket = ["X", "or", "Z"]

if "or" in bracket:
   index_of_or = bracket.index("or")
   if (bracket[index_of_or -1 ] or bracket[index_of_or +1]) in sentence:
      bracket = "True"
      print(bracket)
   else:
      bracket = "False"
      print(bracket)

產量

False

發生此問題是由於以下語句:

if bracket[index_of_or -1 ] or bracket[index_of_or +1] in sentence:

實際上,它所做的事情與看上去的有所不同。 如果滿足以下任一條件,則評估為true:

  • bracket[index_of_or -1 ]計算結果為true,或者

  • bracket[index_of_or +1] in sentence計算為true。

但您認為如果滿足以下任一條件,則評估結果為true:

  • bracket[index_of_or -1 ] in sentence計算為true,或者

  • bracket[index_of_or +1] in sentence計算為true。

如果數字不為0,則第一個條件(方bracket[index_of_or -1 ] )將被評估為True這將被評估為False因為index_of_or = bracket.index("or")返回1,而方bracket[index_of_or -1 ]使它為0,因此使其值為False

要修復它,只需將程序更改為此:

sentence = ["A", "B", "C"]
bracket = ["X", "or", "B"]

if "or" in bracket:
   index_of_or = bracket.index("or")
   if (bracket[index_of_or -1 ] or bracket[index_of_or +1]) in sentence:
      bracket = "True"
      print(bracket)
   else:
      bracket = "False"
      print(bracket)

並且輸出將為False ,如預期的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM