2017-02-12 152 views
-2
def main(): 
x = input("print data? (Y/N) ") 

while (x != 'Y' or x != 'N'): 
    x = input("error: wrong input. Please put Y or N only ") 

if x == 'Y': 
    read_serial() 

嘗試檢查鍵盤輸入(x)是否等於'Y'或'N'字符串。如果沒有,那麼循環會繼續下去,直到它結束。然而,上面的代碼似乎編譯和運行良好,除了無論循環保持運行。沒有太多的Python 3經驗,所以任何人都可以告訴我我做錯了什麼?Python:如何將input()字符串與另一個字符串進行比較?

+0

@ tigerhawkT3我不認爲這是正確的副本。 – Maroun

+0

@MarounMaroun - 當然是。添加一個'not'(例如'x not in'YN'')是微不足道的。 – TigerhawkT3

回答

1

本聲明

x != 'Y' or x != 'N' 

總是True,因爲一切都在世界上是不是 「Y」 或沒有 「N」。

將其更改爲:

x != 'Y' and x != 'N' 
0

更改orand,因爲你要檢查它不等於到這些領域。如果你想使用or你將不得不更改代碼以

def main(): 
    user_input = input("print data? (Y/N) ") 

    while (true): 
     if (user_input.lower() == 'y' or user_input.lower() == 'n'): 
      break 
     user_input = input("error: wrong input. Please put Y or N only ") 

    if user_input.lower() == 'y': 
     read_serial() 

側面說明:x是一個貧窮的變量名,調用它更合適些。

當大小寫無關緊要時,您應該在比較字符串時將case降低。在這種情況下,案件並不重要,所以使用lower()

def main(): 
    user_input = input("print data? (Y/N) ") 

    while (user_input.lower() != 'y' and user_input.lower() != 'n'): 
     user_input = input("error: wrong input. Please put Y or N only ") 

    if user_input.lower() == 'y': 
     read_serial() 
相關問題